React Native之本地文件系统访问组件react-native-fs的介绍与使用
React Native之本地文件系统访问组件react-native-fs的介绍与使用
一,需求分析
1,需要将图片保存到本地相册;
2,需要创建文件,并对其进行读写 删除操作。
二,简单介绍
react-native-fs支持以下功能(ios android):
- 将文本写入本地 txt
- 读取txt文件内容
- 在已有的txt上添加新的文本
- 删除文件
- 下载文件(图片、文件、视频、音频)
- 上传文件 only iOS
三,使用实例
3.1 将文本写入本地 txt
let rnfsPath = Platform.OS === 'ios' ? RNFS.LibraryDirectoryPath : RNFS.ExternalDirectoryPath
const path = rnfsPath + '/test_' +uid + '.txt';
//write the file
RNFS.writeFile(path, test, 'utf8')
.then((success) => {
alert('path=' + path);
})
.catch((err) => {
console.log(err)
});
3.2 读取txt文件内容
let rnfsPath = Platform.OS === 'ios'? RNFS.LibraryDirectoryPath:RNFS.ExternalDirectoryPath
const path = rnfsPath+ '/keystore_'+.uid+'.txt';
//alert(RNFS.CachesDirectoryPath)
return RNFS.readFile(path)
.then((result) => {
Toast.show('读取成功')
})
.catch((err) => {
//alert(err.message);
Toast.show('读取失败');
});
3.3 在已有的txt上添加新的文本
/*在已有的txt上添加新的文本*/
appendFile() {
let rnfsPath = Platform.OS === 'ios'? RNFS.LibraryDirectoryPath:RNFS.ExternalDirectoryPath
const path = rnfsPath+ '/test_'+uid+'.txt';
return RNFS.appendFile(path, '新添加的文本', 'utf8')
.then((success) => {
console.log('success');
})
.catch((err) => {
console.log(err.message);
});
}
3.4 删除文件
/*删除文件*/
deleteFile() {
// create a path you want to delete
let rnfsPath = Platform.OS === 'ios'? RNFS.LibraryDirectoryPath:RNFS.ExternalDirectoryPath
const path = rnfsPath+ '/test_'+uid+'.txt';
return RNFS.unlink(path)
.then(() => {
//alert('FILE DELETED');
})
.catch((err) => {
//console.log(err.message);
});
}
3.5 下载文件(图片、文件、视频、音频)
export const downloadFile =(uri,callback)=> {
if (!uri) return null;
return new Promise((resolve, reject) => {
let timestamp = (new Date()).getTime();//获取当前时间错
let random = String(((Math.random() * 1000000) | 0))//六位随机数
let dirs = Platform.OS === 'ios' ? RNFS.LibraryDirectoryPath : RNFS.ExternalDirectoryPath; //外部文件,共享目录的绝对路径(仅限android)
const downloadDest = `${dirs}/${timestamp+random}.jpg`;
//const downloadDest = `${dirs}/${timestamp+random}.zip`;
//const downloadDest = `${dirs}/${timestamp+random}.mp4`;
//const downloadDest = `${dirs}/${timestamp+random}.mp3`;
const formUrl = uri;
const options = {
fromUrl: formUrl,
toFile: downloadDest,
background: true,
begin: (res) => {
// console.log('begin', res);
// console.log('contentLength:', res.contentLength / 1024 / 1024, 'M');
},
progress: (res) => {
let pro = res.bytesWritten / res.contentLength;
callback(pro);//下载进度
} };
try {
const ret = RNFS.downloadFile(options);
ret.promise.then(res => {
// console.log('success', res);
// console.log('file://' + downloadDest)
var promise = CameraRoll.saveToCameraRoll(downloadDest);
promise.then(function(result) {
// alert('保存成功!地址如下:\n' + result);
}).catch(function(error) {
console.log('error', error);
// alert('保存失败!\n' + error);
});
resolve(res);
}).catch(err => {
reject(new Error(err))
});
} catch (e) {
reject(new Error(e))
} }) }
3.6 上传文件 only iOS(官网实例)
var uploadUrl = 'http://requestb.in/XXXXXXX'; // For testing purposes, go to http://requestb.in/ and create your own link
// create an array of objects of the files you want to upload
var files = [
{
name: 'test1',
filename: 'test1.w4a',
filepath: RNFS.DocumentDirectoryPath + '/test1.w4a',
filetype: 'audio/x-m4a'
}, {
name: 'test2',
filename: 'test2.w4a',
filepath: RNFS.DocumentDirectoryPath + '/test2.w4a',
filetype: 'audio/x-m4a'
}
]; var uploadBegin = (response) => {
var jobId = response.jobId;
console.log('UPLOAD HAS BEGUN! JobId: ' + jobId);
}; var uploadProgress = (response) => {
var percentage = Math.floor((response.totalBytesSent/response.totalBytesExpectedToSend) * 100);
console.log('UPLOAD IS ' + percentage + '% DONE!');
}; // upload files
RNFS.uploadFiles({
toUrl: uploadUrl,
files: files,
method: 'POST',
headers: {
'Accept': 'application/json',
},
fields: {
'hello': 'world',
},
begin: uploadBegin,
progress: uploadProgress
}).promise.then((response) => {
if (response.statusCode == 200) {
console.log('FILES UPLOADED!'); // response.statusCode, response.headers, response.body
} else {
console.log('SERVER ERROR');
}
})
.catch((err) => {
if(err.description === "cancelled") {
// cancelled by user
}
console.log(err);
});
React Native之本地文件系统访问组件react-native-fs的介绍与使用的更多相关文章
- Blazor组件自做十一 : File System Access 文件系统访问 组件
Blazor File System Access 文件系统访问 组件 Web 应用程序与用户本地设备上的文件进行交互 File System Access API(以前称为 Native File ...
- 【React】学习笔记(一)——React入门、面向组件编程、函数柯里化
课程原视频:https://www.bilibili.com/video/BV1wy4y1D7JT?p=2&spm_id_from=pageDriver 目录 一.React 概述 1.1.R ...
- React学习(一)父子组件通讯
React父子组件之间通讯,利用props和state完成,首先React是单向数据流,父组件可以向子组件传递props: 实现父子组件双向数据流整体的思路是: 1,父组件可以向子组件传递props, ...
- React(0.13) 定义一个input组件,使其输入的值转为大写
<!DOCTYPE html> <html> <head> <title>React JS</title> <script src=& ...
- React Native v0.4 发布,用 React 编写移动应用
React Native v0.4 发布,自从 React Native 开源以来,包括超过 12.5k stars,1000 commits,500 issues,380 pull requests ...
- 2.react 基础 - create-react-app 目录结构 及 组件应用
1. react-app 脚手架的 目录结构 node_modules -d 存放 第三方下载的 依赖的包 public -d 资源目录 favicon.ico - 左上角的图标 index.h ...
- React使用笔记2--创建登录组件
文章目录 最近在学习使用React作为前端的框架,<React使用笔记>系列用于记录过程中的一些使用和解决方法.本文记录搭建登录页面的过程. 根据产品规划划分模块 主要页面逻辑 在这里,本 ...
- 重新想象 Windows 8 Store Apps (22) - 文件系统: 访问文件夹和文件, 通过 AQS 搜索本地文件
原文:重新想象 Windows 8 Store Apps (22) - 文件系统: 访问文件夹和文件, 通过 AQS 搜索本地文件 [源码下载] 重新想象 Windows 8 Store Apps ( ...
- 【每天半小时学框架】——React.js的模板语法与组件概念
[重点提前说:组件化与虚拟DOM是React.js的核心理念!] 先抛出一个论题:在React.js中,JSX语法提倡将 HTML 和 CSS 全都写入到JavaScrip ...
随机推荐
- Python爬虫-02:HTTPS请求与响应,以及抓包工具Fiddler的使用
目录 1. HTTP和HTTPS 1.1. HTTP的请求和响应流程:打开一个网页的过程 1.2. URL 2. 客户端HTTP请求 3. Fiddler抓包工具的使用 3.1. 工作原理 3.2. ...
- Fetch请求后台的数据
<style> #btn{ width: 50px; height: 50px; background-color: red; } #output{ width: 100px; heigh ...
- python3内置函数练习
1. abs() abs() 函数返回数字的绝对值. print(abs(1.5236)) # 1.5236 print(abs(1.0)) # 1.0 2. all() all() 函数用于判断给定 ...
- 查看linux内存使用情况
查看内存使用情况 free -m total used free shared buffers cached Mem: -/+ buffers/cache: Swap: used=total-free ...
- UVA116-Unidirectional TSP(动态规划基础)
Problem UVA116-Unidirectional TSP Accept: 7167 Submit: 56893Time Limit: 3000 mSec Problem Descripti ...
- 获取列表的索引操作:enumerate
通过循环获取列表的索引操作: 主要使用:enumerate product_list = [['Iphone7',5800], ['Coffee',30], ['疙瘩汤',10], ['Python ...
- java爬虫代理
public static Document getDocByJsoups(String href) { String ip = "124.47.7.38"; int port = ...
- node.js之十大Web框架
之前接触过Node.js是因为好奇大前端越来越能干了,连我后台的饭碗都要抢了,太嚣张了,于是我想打压打压它,然后就这样接触它了.再到后来是因为Settings-Sync插件二次开发,我需要用node. ...
- SpringBoot之加密
最近利用闲暇时间写了一个博客系统,主要参考wordpress,主要目的是为了提高自己的技术能力.写代码写了两年多,联系到之前在学校的时候写过的一个博客系统,发现工作中开发的系统,技术上基本一致,业务逻 ...
- lightoj-1128-Greatest Parent(二分+LCA)
传送门 首先我要实力吐槽这个lightoj 它给我的注册密码藏在不为人所见的地方 注册注册了10多分钟 qwq -------------------------------------------- ...