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. NGINX Load Balancing - HTTP Load Balancer

    This chapter describes how to use NGINX and NGINX Plus as a load balancer. Overview Load balancing a ...

  2. 2292: Quality of Check Digits 中南多校 暴力枚举

    #include <cstdio> #include <algorithm> #include <cstring> #include <iostream> ...

  3. 11.redis_python

    # pip install redis import redis # 1.链接数据库 key--value client = redis.StrictRedis(host='127.0.0.1', p ...

  4. 前端导出excel表

    前端导出excel表 方式一: 前端js实现 : https://www.cnblogs.com/zhangym118/p/6235801.html 方式二: java后端实现: https://bl ...

  5. [MCM] K-mean聚类与DBSCAN聚类 Python

    import matplotlib.pyplot as plt X=[56.70466067,56.70466067,56.70466067,56.70466067,56.70466067,58.03 ...

  6. js截取url参数

    举例说明,比如http://localhost:2019/blog/getCommentListInfo?postId=1如何获取postId=1这个参数值呢?很简单通过下面代码即可获取,如: win ...

  7. glance系列一:glance基础

    一 什么是glance glance即image service,是为虚拟机的创建提供镜像的服务 二 为何要有glance 我们基于openstack是构建基本的Iaas平台对外提供虚拟机,而虚拟机在 ...

  8. Mysql字段名与保留字冲突导致的异常解决

    一:引言 用hibernate建表时经常遇到的一个异常:Error executing DDL via JDBC Statement 方法: 查看报错sql语句.问题就在这里. 我是表名(字段名)与保 ...

  9. ProxySQL+Mysql实现数据库读写分离实战

    ProxySQL介绍 ProxySQL是一个高性能的MySQL中间件,拥有强大的规则引擎.具有以下特性:http://www.proxysql.com/ 1.连接池,而且是multiplexing 2 ...

  10. .Net外包篇:我是如何看待外包的

    前言 从工作至今,我在工作之余大大小小接了六次外包,不多不少,虽然没有为我带来很大收益,但也让我开拓了人脉,接触了不少知识,锻炼了全栈开发能力. 菜鸟时代 第一家客户(成功) 我接的第一个外包是为一家 ...