Как я могу загрузить через WebView с помощью react-native?

Я использую WebView, и я хочу, чтобы человек загрузил его через WebView. Это простой WebView, у которого есть ссылка для загрузки zip-файла.

Могу ли я использовать веб-просмотр? (Как Chrome)

по крайней мере, я хочу получить слушателя, когда пользователь пытается загрузить файл через WebView.

5
0
9 325
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Я сделал так, чтобы загрузить файл, нам нужно два шага, получить биты и создать файл на устройстве, в этом примере я загружаю любой файл .zip, когда URL-адрес имеет .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.info('FOLDER/FILE DELETED');
        })
        // `unlink` will throw an error, if the item to unlink does not exist
        .catch((err) => {
          console.info('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.info(e);
          fileName = 'example.zip'
        }

        console.info('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.info('progress', received / total)
          })
          .then((res) => {
            // the path should be dirs.DocumentDir + 'path-to-file.anything'
            console.info('The file saved to ', res.path())

            //Acabou o download do arquivo
            this.setState({
              downloadStart: false, showModalLoading: false,
              showFileExplorer: true, startFolder: directoryFile
            })
          })
      }
    }
  }

Для оригинального WebViewhttps://github.com/react-native-community/react-native-webview существует компонент для замены, который поддерживает загрузку (и выгрузку) файлов с декабря 2018 года.

Все, что вам нужно, это добавить разрешения для iOS, добавив следующее в ios/[project]/Info.plist:

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

или для Android, добавив это в AndroidManifest.xml

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

Другие вопросы по теме