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