首页 > 解决方案 > 从 React Native WebView 下载文件

问题描述

背景

我正在使用 WebView 将用户导航到下载文件的特定页面。我将 Javascript 注入 WebView 以模拟单击下载文件链接。使用 Javascript 单击链接后,该文件将在设备上打开。

我正在尝试查找将文件下载到设备的信息,而不是在 WebView 中打开它。

最初我在 IOS 中构建了这个应用程序,在那里我能够将数据作为 blob 下载,然后使用 API 将其发送到我的服务器。我想模拟相同类型的功能。

例子

// 这会在 WebView 中打开文件

  const injectedJavaScript = `var confirmLink = document.querySelector("a[href='/file/download']");
      if(confirmLink) { window.location.href = confirmLink.href; }
      `;
      this.setState({ step: "complete" });
      this.webview.injectJavaScript(injectedJavaScript);

问题

如何在不在手机上打开它的情况下使用此文件?理想情况下,我希望将文件作为 blob 处理,但是我很乐意将文件下载到手机的存储中,然后可以从那里使用它。

标签: react-native

解决方案


回答 -

从流中读取文件并将其作为 base64 使用。您可以将文件转换为 base64 并将其移动到您想要的任何位置。

例子 -

这个例子是我注入 JavaScript 来访问 Web 服务器上的文件。该文件将转换为 base64 字符串。然后我将该文件发布到我的 API 并转换回服务器上的文件。然后该文件位于我的服务器上。

const injectedJavaScript = `
      fetch("https://www.example.com/somepath.do?language=en", {
        method: "GET",
        headers: new Headers({
          Accept:
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
          "Accept-Encoding": "gzip, deflate, sdch, br",
          "Accept-Language": "en-US,en;q=0.8",
          Connection: "keep-alive",
          Referer:
            "https://www.example.com/somepath.do",
          "User-Agent":
            "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301",
          "Content-Disposition": "attachment; filename=someFile.txt"
        })
      })
        .then(response => {
          response.body.getReader().read().then(function(result) {
             return btoa(String.fromCharCode.apply(null, result.value));
         }).then(function(b64) {
             fetch("https://api.example.com/api/v1/endpoint", {
               method: "POST",
               headers: {
                 "Content-Type": "application/json"
               },
               body: JSON.stringify({
               data: b64
               })
             }).then(res => {
               console.log(res);
             }).catch(e => {
               console.log(e);
           });
        });
      });
        `;

推荐阅读