如何使用 react-native 通过 WebView 下载?



我正在使用WebView,我想让这个人通过WebView下载。 这是一个简单的WebView,其中包含下载zip文件的链接。

我可以使用网络视图吗?(如铬(

至少我想在用户尝试通过WebView下载文件时获取侦听器。

我以这种方式做了,要下载文件,我们需要两个步骤,获取位并在设备上创建一个文件,在此示例中,当 url 有.zip时,我将下载任何.zip文件:

我正在使用:

import RNFetchBlob from 'rn-fetch-blob';
var RNFS = require('react-native-fs');

并像这样使用WebView

<WebView
source={{ uri: "http://myinitialurl.com.br/arquivos/" }}
style={{}}
startInLoadingState={true}
allowUniversalAccessFromFileURLs={true}
javaScriptEnabled={true}
mixedContentMode={'always'}
onNavigationStateChange={(result) => this.handleUrlWithZip(result)}
/>

和:

handleUrlWithZip(input) {
//check if have another download
if (this.state.downloadStart == true || input.url.toLowerCase().includes('.zip') == false) {
return;
} else {
this.setState({ downloadStart: true, showModalLoading: true })
}
const directoryFile = RNFS.ExternalStorageDirectoryPath + '/DownloadFile/';
//Creating folder
if (RNFS.exists(directoryFile)) {
RNFS.unlink(directoryFile)
.then(() => {
console.log('FOLDER/FILE DELETED');
})
// `unlink` will throw an error, if the item to unlink does not exist
.catch((err) => {
console.log('CANT DELETE', err.message);
this.setState({ showError: true })
});
RNFS.mkdir(directoryFile)
}
//If folder is created
if (input) {
//Verifing if the url have a .zip file
if (input.url.toLowerCase().includes('.zip')) {
const urlDownload = input.url;
let fileName;
try {
fileName = urlDownload.substr(urlDownload.lastIndexOf('/')).replace('.zip', '') + '.zip';
} catch (e) {
console.log(e);
fileName = 'example.zip'
}
console.log('URL = ' + urlDownload)
//Downloading the file on a folder
let dirs = directoryFile + '/' + fileName;
RNFetchBlob
.config({
// response data will be saved to this path if it has access right.
path: dirs
})
.fetch('GET', urlDownload, {
//some headers ..
})
.progress((received, total) => {
console.log('progress', received / total)
})
.then((res) => {
// the path should be dirs.DocumentDir + 'path-to-file.anything'
console.log('The file saved to ', res.path())
//Acabou o download do arquivo
this.setState({
downloadStart: false, showModalLoading: false,
showFileExplorer: true, startFolder: directoryFile
})
})
}
}
}

自 2018 年 12 月起,原始WebViewhttps://github.com/react-native-community/react-native-webview 有一个插入式替换组件,支持文件下载(和上传(。

您所需要的只是通过将以下内容添加到iOSios/[project]/Info.plist来添加权限:

<key>NSPhotoLibraryAddUsageDescription</key>
<string>Save pictures for certain activities.</string>

或者通过将其添加到AndroidManifest.xml对于安卓

<!-- this is required to save files on Android  -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

最新更新