gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 13:46:47 25 4
gpt4 key购买 nike

我正在使用 WebView,我想让用户通过 WebView 下载。这是一个简单的 WebView,它有一个下载 zip 文件的链接。

我可以使用 WebView 吗? (像 Chrome)

至少我想在用户尝试通过 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
})
})
}
}
}

关于android - 如何使用 react-native 通过 WebView 下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52366613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com