React Native之本地文件系统访问组件react-native-fs的介绍与使用

时间:2023-03-10 04:57:16
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);
});