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

 1  let rnfsPath = Platform.OS === 'ios' ? RNFS.LibraryDirectoryPath : RNFS.ExternalDirectoryPath
 2         const path = rnfsPath + '/test_' +uid + '.txt';
 3         //write the file
 4         RNFS.writeFile(path, test, 'utf8')
 5             .then((success) => {
 6                 alert('path=' + path);
 7             })
 8             .catch((err) => {
 9                console.log(err)
10 });

    3.2 读取txt文件内容

 1  let rnfsPath = Platform.OS === 'ios'? RNFS.LibraryDirectoryPath:RNFS.ExternalDirectoryPath
 2         const path =  rnfsPath+ '/keystore_'+.uid+'.txt';
 3         //alert(RNFS.CachesDirectoryPath)
 4         return RNFS.readFile(path)
 5             .then((result) => {
 6                 Toast.show('读取成功')
 7             })
 8         .catch((err) => {
 9            //alert(err.message);
10             Toast.show('读取失败');
11         });

    3.3 在已有的txt上添加新的文本

 1 /*在已有的txt上添加新的文本*/
 2     appendFile() {
 3       let rnfsPath = Platform.OS === 'ios'? RNFS.LibraryDirectoryPath:RNFS.ExternalDirectoryPath
 4          const path =  rnfsPath+ '/test_'+uid+'.txt';
 5         return RNFS.appendFile(path, '新添加的文本', 'utf8')
 6             .then((success) => {
 7                 console.log('success');
 8             })
 9             .catch((err) => {
10                 console.log(err.message);
11             });
12     }

    3.4 删除文件

 1  /*删除文件*/
 2     deleteFile() {
 3         // create a path you want to delete
 4         let rnfsPath = Platform.OS === 'ios'? RNFS.LibraryDirectoryPath:RNFS.ExternalDirectoryPath
 5         const path =  rnfsPath+ '/test_'+uid+'.txt';
 6         return RNFS.unlink(path)
 7             .then(() => {
 8                //alert('FILE DELETED');
 9             })
10             .catch((err) => {
11                 //console.log(err.message);
12             });
13     }

3.5 下载文件(图片、文件、视频、音频)

 1 export const downloadFile =(uri,callback)=> {
 2     if (!uri) return null;
 3     return new Promise((resolve, reject) => {
 4         let timestamp = (new Date()).getTime();//获取当前时间错
 5         let random = String(((Math.random() * 1000000) | 0))//六位随机数
 6         let dirs = Platform.OS === 'ios' ? RNFS.LibraryDirectoryPath : RNFS.ExternalDirectoryPath; //外部文件,共享目录的绝对路径(仅限android)
 7         const downloadDest = `${dirs}/${timestamp+random}.jpg`;
 8         //const downloadDest = `${dirs}/${timestamp+random}.zip`;
 9          //const downloadDest = `${dirs}/${timestamp+random}.mp4`;
10           //const downloadDest = `${dirs}/${timestamp+random}.mp3`;
11         const formUrl = uri;
12         const options = {
13             fromUrl: formUrl,
14             toFile: downloadDest,
15             background: true,
16             begin: (res) => {
17                 // console.log('begin', res);
18                 // console.log('contentLength:', res.contentLength / 1024 / 1024, 'M');
19             },
20 progress: (res) => {
21                 let pro = res.bytesWritten / res.contentLength;
22                callback(pro);//下载进度
23             }
24 
25         };
26         try {
27             const ret = RNFS.downloadFile(options);
28             ret.promise.then(res => {
29                 // console.log('success', res);
30                 // console.log('file://' + downloadDest)
31                 var promise = CameraRoll.saveToCameraRoll(downloadDest);
32                 promise.then(function(result) {
33                    // alert('保存成功!地址如下:\n' + result);
34                 }).catch(function(error) {
35                      console.log('error', error);
36                     // alert('保存失败!\n' + error);
37                 });
38                 resolve(res);
39             }).catch(err => {
40                 reject(new Error(err))
41             });
42         } catch (e) {
43             reject(new Error(e))
44         }
45 
46     })
47 
48 }

3.6 上传文件 only iOS(官网实例)

 1 var uploadUrl = 'http://requestb.in/XXXXXXX';  // For testing purposes, go to http://requestb.in/ and create your own link
 2 // create an array of objects of the files you want to upload
 3 var files = [
 4   {
 5     name: 'test1',
 6     filename: 'test1.w4a',
 7     filepath: RNFS.DocumentDirectoryPath + '/test1.w4a',
 8     filetype: 'audio/x-m4a'
 9   }, {
10     name: 'test2',
11     filename: 'test2.w4a',
12     filepath: RNFS.DocumentDirectoryPath + '/test2.w4a',
13     filetype: 'audio/x-m4a'
14   }
15 ];
16 
17 var uploadBegin = (response) => {
18   var jobId = response.jobId;
19   console.log('UPLOAD HAS BEGUN! JobId: ' + jobId);
20 };
21 
22 var uploadProgress = (response) => {
23   var percentage = Math.floor((response.totalBytesSent/response.totalBytesExpectedToSend) * 100);
24   console.log('UPLOAD IS ' + percentage + '% DONE!');
25 };
26 
27 // upload files
28 RNFS.uploadFiles({
29   toUrl: uploadUrl,
30   files: files,
31   method: 'POST',
32   headers: {
33     'Accept': 'application/json',
34   },
35   fields: {
36     'hello': 'world',
37   },
38   begin: uploadBegin,
39   progress: uploadProgress
40 }).promise.then((response) => {
41     if (response.statusCode == 200) {
42       console.log('FILES UPLOADED!'); // response.statusCode, response.headers, response.body
43     } else {
44       console.log('SERVER ERROR');
45     }
46   })
47   .catch((err) => {
48     if(err.description === "cancelled") {
49       // cancelled by user
50     }
51     console.log(err);
52   });

猜你喜欢

转载自www.cnblogs.com/jackson-zhangjiang/p/9554611.html