《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/;
    }

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值