react-native-fs插件使用案列详解

php中世界最好的语言
php中世界最好的语言 原创
2018-04-18 09:09:35 1839浏览

这次给大家带来react-native-fs插件使用案列详解,react-native-fs插件使用的注意事项有哪些,下面就是实战案例,一起来看一下。

react-native-fs插件是文件对上传和下载时使用的,iOS和android都可使用,File upload (iOS only)。

安装命令:

npm install react-native-fs --save
//注意:如果react native版本是<0.40安装,使用此标签:
npm install react-native-fs@2.0.1-rc.2 --save

安装后执行:

react-native link react-native-fs

在android/app/src/main/AndroidManifest.xml,里添加android读写文件的权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

进行完上述安装操作后,可以使用这个插件的各种方法,每个方法的具体使用例子,请看链接:https://github.com/itinance/react-native-fs。在项目里我需要下载图片文件,并获得下载到本地后的图片路径,然后显示图片。所以使用到downloadFile方法。封装了一个可调用的服务,代码如下:

downloadFile(imageId, cookie, callback) {
    const downloadDest = `${RNFS.DocumentDirectoryPath}/${((Math.random() * 1000) | 0)}.jpg`;
    var formUrl = CommonSvc.baseURL + '/api/image/0/' + imageId;
    //var formUrl = 'http://lorempixel.com/400/200/';
    const options = {
      fromUrl: formUrl,
      toFile: downloadDest,
      background: true,
      headers: {
        'Cookie': cookie //需要添加验证到接口要设置cookie
      },
      begin: (res) => {
        //console.log(res);
      },
      progress: (res) => {
        //console.log(res);
      }
    };
    try {
      const ret = RNFS.downloadFile(options);
      ret.promise.then(res => {
        //callback(null, Platform.OS === 'android' ? downloadDest : 'file://' + downloadDest)
        callback(null, 'file://' + downloadDest)
 
      }).catch(err => {
        callback(err)
      });
    }
    catch (e) {
      callback("error")
    }
 
  },

在实现这个功能到时候,android下载到本地的图片显示不出来,这个查阅了相关资料后,原因是android调用此插件,需要添加接口验证信息(如果接口是需要验证的情况下),这个问题怎么解决呢

调用react-native-fs插件时,如果数据的接口是需要验证信息的,在android上运行报错,而在iOS上运行没问题。原因是因为接口是有验证信息的,而调用这个插件时没有传入,在iOS上会自动加上验证信息,而 android需要手动设置。

此错误的解决方法:

1.在调用登录接口时,保存下cookie(cookie在response里),在调用react-native-fs时放在headers里传入,代码如下:

_appLogin(userName, password, callback){
 
    fetch(commonSvc.baseURL + '/account/app-login', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        UserName: userName,
        Password: password
      })
    }).then(
      (response) => {
        if (response.ok) {
          return response;
        } else {
          var message;
          switch (response.status) {
            case 710:
              message = LanguageChooseSvc.strings['api_common_' + 710];
              break;
            case 711:
              message = LanguageChooseSvc.strings['api_common_' + 711];
              break;
            case 400:
              message = LanguageChooseSvc.strings['api_common_' + 400];
              break;
            default:
              message = commonSvc.httpErrorMessage;
              break;
          }
          throw {message: message};
        }
      }
    ).then(
      (responseJson) => {
        callback(null, responseJson);
      }
    ).catch(
      (error) => {
        callback(error.message);
      }
    );
  },

2.在调用react-native-fs时放在headers里传入,代码如下:

 downloadFile(imageId, cookie, callback) {
    const downloadDest = `${RNFS.DocumentDirectoryPath}/${((Math.random() * 1000) | 0)}.jpg`;
    var formUrl = CommonSvc.baseURL + '/api/image/0/' + imageId;
    //var formUrl = 'http://lorempixel.com/400/200/';
    const options = {
      fromUrl: formUrl,
      toFile: downloadDest,
      background: true,
      headers: {
        'Cookie': cookie //需要添加验证到接口要设置cookie
      },
      begin: (res) => {
        //console.log(res);
      },
      progress: (res) => {
        //console.log(res);
      }
    };
    try {
      const ret = RNFS.downloadFile(options);
      ret.promise.then(res => {
        //callback(null, Platform.OS === 'android' ? downloadDest : 'file://' + downloadDest)
        callback(null, 'file://' + downloadDest)
 
      }).catch(err => {
        callback(err)
      });
    }
    catch (e) {
      callback("error")
    }
 
  },

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

js实现字符限制中文汉字=两个字符

用js实现汽车仪表盘

以上就是react-native-fs插件使用案列详解的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。