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

Sil*_*spo 5 android react-native

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

我可以使用 webview 吗?(像铬)

至少我想在用户尝试通过WebView.

Sil*_*spo 3

我这样做了,要下载文件,我们需要两个步骤,获取位并在设备上创建文件,在本示例中,.zip当网址具有以下内容时,我将下载任何文件.zip

我在用着 :

import RNFetchBlob from 'rn-fetch-blob';
var RNFS = require('react-native-fs');
Run Code Online (Sandbox Code Playgroud)

并使用WebView这样的:

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

和:

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
            })
          })
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)