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的介绍与使用的更多相关文章

  1. Blazor组件自做十一 : File System Access 文件系统访问 组件

    Blazor File System Access 文件系统访问 组件 Web 应用程序与用户本地设备上的文件进行交互 File System Access API(以前称为 Native File ...

  2. 【React】学习笔记(一)——React入门、面向组件编程、函数柯里化

    课程原视频:https://www.bilibili.com/video/BV1wy4y1D7JT?p=2&spm_id_from=pageDriver 目录 一.React 概述 1.1.R ...

  3. React学习(一)父子组件通讯

    React父子组件之间通讯,利用props和state完成,首先React是单向数据流,父组件可以向子组件传递props: 实现父子组件双向数据流整体的思路是: 1,父组件可以向子组件传递props, ...

  4. React(0.13) 定义一个input组件,使其输入的值转为大写

    <!DOCTYPE html> <html> <head> <title>React JS</title> <script src=& ...

  5. React Native v0.4 发布,用 React 编写移动应用

    React Native v0.4 发布,自从 React Native 开源以来,包括超过 12.5k stars,1000 commits,500 issues,380 pull requests ...

  6. 2.react 基础 - create-react-app 目录结构 及 组件应用

    1. react-app 脚手架的 目录结构 node_modules -d 存放 第三方下载的 依赖的包 public -d    资源目录 favicon.ico - 左上角的图标 index.h ...

  7. React使用笔记2--创建登录组件

    文章目录 最近在学习使用React作为前端的框架,<React使用笔记>系列用于记录过程中的一些使用和解决方法.本文记录搭建登录页面的过程. 根据产品规划划分模块 主要页面逻辑 在这里,本 ...

  8. 重新想象 Windows 8 Store Apps (22) - 文件系统: 访问文件夹和文件, 通过 AQS 搜索本地文件

    原文:重新想象 Windows 8 Store Apps (22) - 文件系统: 访问文件夹和文件, 通过 AQS 搜索本地文件 [源码下载] 重新想象 Windows 8 Store Apps ( ...

  9. 【每天半小时学框架】——React.js的模板语法与组件概念

           [重点提前说:组件化与虚拟DOM是React.js的核心理念!]        先抛出一个论题:在React.js中,JSX语法提倡将 HTML 和 CSS 全都写入到JavaScrip ...

随机推荐

  1. 【FJWC 2019】min

    [FJWC 2019]min 题目描述 给你一张 \(n\) 个点 \(m\) 条边的无向图,走过每条边都需要花费 \(1\) 秒. 给你一个整数 \(k\) ,请你选择至多 \(k\) 个点,令经过 ...

  2. sqlSugar的使用---入门

    一,新建.net core  web项目 二.  项目引入包:sqlSugarCore 三.创建两个表:user,   department 四. 新建model(不一定需要与table相同,使用[S ...

  3. centos7下安装docker(18docker日志---docker logs)

    在微服务架构中,由于容器的数量众多以及快速变化的特性使得记录日志和监控变得越来越重要,考虑到容器的短暂和不固定周期,当我们需要排查问题的时候容器可能不在了.因此,一套集中式的日志管理系统是生产环境中不 ...

  4. zabbix 应用监控作业笔记 ansible-playbook

    目录 目录结构 zabbix-web.yaml zabbix-backup.yaml zabbix-nfs.yaml zabbix-mysql.yaml zabbix-server.yaml zabb ...

  5. 【vue】钩子函数生命周期

    图1 图2: 图3 相关资料:http://www.zhimengzhe.com/Javascriptjiaocheng/236707.html    https://segmentfault.com ...

  6. 3.if结构

    一.简单if结构1.定义:程序的条件判断2.语法:if(条件){ 语句块1}else{ 语句块2}语句块33:说明:条件必须是条件表达式,其结果必须是一个boolean类型 else是可选项,可以不写 ...

  7. RMAN_RAC归档日志备份包恢复到单机

    恢复归档日志的方法: RAC是ASM的存储且是OMF创建的格式,所以RAC的日志名为如下+ARCH/mioa/archive/1_73554_875548170.dbf.+ARCH/mioa/arch ...

  8. Python 绑定 C,C++ 参考工具介绍

    https://wiki.python.org/moin/IntegratingPythonWithOtherLanguages 完.

  9. 关于tomcat启动报“this web application instance has been stopped already”的处理

      出现情况1            启动tomcat的时候,默认会启动这个“/tomcat/webapps/ROOT”路径下的tomcat自带的程序包,当启动这个路径下的程序包后,如果tomcat扫 ...

  10. Java的错误类型

    程序的错误分为:编译期语法错误.运行期异常错误和运行期逻辑错误 (1)编译期语法错误可以借助Eclipse的帮助方便地定位错误,并进行修改 如: (2)运行期异常,即 没有语法错误,编译可以通过,但运 ...