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 ...
随机推荐
- Oauth2.0[笔记]
背景 如果资源服务器只是提供资源给自己的应用,使用帐号密码做身份认证倒没什么问题,但如果需要提供资源给第三方应用,就会出现第三方应用需要与资源服务器共享身份凭证,这时会出现几个问题: 1.第三方应用需 ...
- Spring的IOC注解开发入门1
基本知识点如下: 引入注解约束,配置组件扫描 类上的注解: @Conponent @Controller @Service @Repository 普通属性的注解 @value 对象属性的注解 ...
- redis学习笔记(一)-安装
检查是否有redis yum 源 yum install redis 下载fedora的epel仓库 yum install epel-release 安装redis数据库 yum install r ...
- java中的闭包
闭包(Closure)是一种能被调用的对象,它保存了创建它的作用域的信息 public class Programmer { private String name; public Programme ...
- vue.js 二维码生成组件
安装 通过NPM安装 npm install vue-qart --save 插件应用 将vue-qart引入你的应用 import VueQArt from 'vue-qart' new Vue({ ...
- spring mybatis整合
mybatis和spring整合的配置方法有很多,核心都是一个矛盾:如何让spring管理mybatis为mapper生成的代理对象. 1.配置数据源 单独使用mybatis的时候数据源是在mybat ...
- 【Vuex】mapGetters 辅助函数
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性: import { mapGetters } from 'vuex' export default { // ...
- 3、原生jdbc链接数据库之锁与事务
一.锁的概念1.作用:是保证数据的一致性,只能一个人修改数据,不能同时多用户修改2.分类:行级锁和表级锁 乐观锁和悲观锁 二.事务1.为了保证数据的一致性和完整性,让数据库的多项操作合并为一个整体 ...
- SpringBoot之静态资源放行
为了提高开发效率,编写对应的代码生成器.代码生成器主要有两个方面,一个是在线Web,另外一个是运行某个类. 使用的技术是SpringBoot+MyBatis-Plus+MySQL+JDK8. 在编写在 ...
- Springboot知识点
1. Spring boot简介 主要用来简化spring开发,快速地创建独立的spring项目,并且与云计算天然集成. 2. @Controller 标记一个类是Controller . 3. @ ...