Home > Web Front-end > JS Tutorial > body text

Detailed explanation of react-native-fs plug-in usage cases

php中世界最好的语言
Release: 2018-04-18 09:09:35
Original
2185 people have browsed it

This time I will bring you a detailed explanation of the usage cases of the react-native-fs plug-in. What are the precautions when using the react-native-fs plug-in? The following is a practical case, let's take a look.

react-native-fs plug-in is used when uploading and downloading files. It can be used on both iOS and android, File upload (iOS only).

Installation command:

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

After installation, execute:

react-native link react-native-fs
Copy after login

In android/app/src/main/AndroidManifest.xml, add android read and write file permissions

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

After completing the above installation operations, you can use various methods of this plug-in. For specific usage examples of each method, please see the link: https://github.com/itinance/react-native-fs. In the project, I need to download the image file, obtain the image path after downloading to the local, and then display the image. So use the downloadFile method. Encapsulates a callable service, the code is as follows:

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")
    }
 
  },
Copy after login

When implementing this function, the pictures downloaded to the local by android cannot be displayed. After consulting the relevant information, the reason is that when android calls this plug-in, it needs to add interface verification information (if the interface needs to be verified) (below), how to solve this problem

When calling the react-native-fs plug-in, if the data interface requires verification information, an error will be reported when running on Android, but there will be no problem when running on iOS. The reason is that the interface has verification information, but it is not passed in when calling this plug-in. On iOS, the verification information will be automatically added, while on Android, it needs to be set manually.

Solution to this error:

1. When calling the login interface, save the cookie (the cookie is in the response), and put it in the headers when calling react-native-fs. The code is as follows:

_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);
      }
    );
  },
Copy after login

2. When calling react-native-fs, pass it in the headers. The code is as follows:

 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")
    }
 
  },
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

js implements character limit Chinese characters = two characters

Using js to implement car dashboard

The above is the detailed content of Detailed explanation of react-native-fs plug-in usage cases. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!