《ReactNatve》使用react-native-fs下載文件

1.安裝react-native-fs

注意版本,npm上是這樣描述的。

For RN < 0.57 and/or Gradle < 3 you MUST install react-native-fs at version @2.11.17!

For RN >= 0.57 and/or Gradle >= 3 you MUST install react-native-fs at version >= @2.13.2!

For RN >= 0.61 please install react-native-fs at version >= @2.16.0!
npm install react-native-fs --save

2. 鏈接

react-native link react-native-fs

3.使用

import RNFS from 'react-native-fs';
_download(){
    const timestamp = (new Date()).getTime();//獲取當前時間錯
    const random = String(((Math.random() * 1000000) | 0))//六位隨機數
    let dirs = Platform.OS === 'ios' ? RNFS.LibraryDirectoryPath : RNFS.ExternalDirectoryPath ; 
    //外部文件,共享目錄的絕對路徑(僅限android)
    const downloadDest = `${dirs}/${timestamp+random}.mp4`;
	//下載地址
    const formUrl = 'http://www.xxx/xxx.mp4';
    const options = {
      fromUrl: formUrl,
      toFile: downloadDest,
      background: true,
      begin: (res) => {
        ToastAndroid.show('開始下載',ToastAndroid.SHORT)
        console.log('begin', res);
        console.log('contentLength:', res.contentLength / 1024 / 1024, 'M');
      },
      progress: (res) => { //下載進度
        let pro = res.bytesWritten / res.contentLength;
        console.log('pro==',pro)
      }
    }
    try {
      const ret = RNFS.downloadFile(options);
      ret.promise.then(res => {
        console.log('success', res);
        console.log('file://' + downloadDest)
		//如果下載的是  視頻或圖片 可以保存到相冊,方便查看
        const promise = CameraRoll.saveToCameraRoll(downloadDest)
        promise.then(result => {
          //alert('保存成功!地址如下:\n' + result);
          //下載成功,請在相冊中查看
          console.log('down res',result);
        }).catch(function(error) {
          console.error('error2', error);
          // alert('保存失敗!\n' + error);
        });
      }).catch(err => {
          console.log('err', err);
      });
    }catch (e) {
      ToastAndroid.show('下載失敗',ToastAndroid.SHORT)
      console.log(error);
    }
  }

下載文件nginx配置

一般下載的文件存放在服務器上,可以用 nginx 來配置訪問規則,比如我下載的是 mp4 文件,mp4文件存放在 d:/mp4/文件夾下,訪問方式爲  nginx地址 : 端口號/文件名.mp4(如 http://192.168.27.41:8090/test.mp4 )

打開nginx 配置文件(nginx.conf),在 server 節點如下配置

location ~* \.(mp4)$ {
        root d:/mp4/;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章