Created
September 11, 2018 06:33
-
-
Save Visionchen/5aa1bfb4b71399a51bf1262fb738ce9f to your computer and use it in GitHub Desktop.
使用react-native-fs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### 插件使用 | |
| ```javascript | |
| yarn add react-native-fs | |
| react-native link react-native-fs | |
| ``` | |
| ### 封装保存图片方法 | |
| ```javascript | |
| /** | |
| * Created by vision on 2018/8/27. | |
| */ | |
| import React from 'react'; | |
| import { Platform, CameraRoll } from 'react-native'; | |
| import RNFS from 'react-native-fs'; | |
| import { Toast} from "teaset" | |
| export function _Download(uri) { | |
| if (!uri) return null; | |
| return new Promise((resolve, reject) => { | |
| let dirs = Platform.OS === 'ios' ? RNFS.LibraryDirectoryPath : RNFS.ExternalDirectoryPath; //外部文件,共享目录的绝对路径(仅限android) | |
| const downloadDest = `${dirs}/${((Math.random() * 10000000) | 0)}.jpg`; | |
| const formUrl = uri; | |
| const options = { | |
| fromUrl: formUrl, | |
| toFile: downloadDest, | |
| background: true, | |
| begin: (res) => { | |
| console.log('begin', res); | |
| console.log('contentLength:', res.contentLength / 1024 / 1024, 'M'); | |
| }, | |
| }; | |
| try { | |
| const ret = RNFS.downloadFile(options); | |
| ret.promise.then(res => { | |
| console.log('success', res); | |
| console.log('file://' + downloadDest) | |
| var promise = CameraRoll.saveToCameraRoll(downloadDest); | |
| promise.then(function(result) { | |
| // alert('保存成功!地址如下:\n' + result); | |
| Toast.success('保存成功!') | |
| }).catch(function(error) { | |
| console.log('error', error); | |
| // alert('保存失败!\n' + error); | |
| Toast.info('保存失败!') | |
| }); | |
| resolve(res); | |
| }).catch(err => { | |
| reject(new Error(err)) | |
| }); | |
| } catch (e) { | |
| reject(new Error(e)) | |
| } | |
| }) | |
| } | |
| ``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment