【问题标题】:Download a file from Cordova InAppBrowser Vue app从 Cordova InAppBrowser Vue 应用程序下载文件
【发布时间】:2020-03-03 22:30:45
【问题描述】:

所以我有一个在网络中运行的 Spring Boot + Vue.js 应用服务器。我还有一个显示前端的 Cordova InAppBrowser Andorid 应用程序。

我必须能够从机器上运行的真实浏览器和 Cordova 应用程序中使用该应用程序。到目前为止效果很好。

但是:当我想从 Cordova 应用程序内的服务器下载 json 格式的文本文件或任何其他文件时,它不起作用。我已经阅读了很多关于这个主题的文章和其他问题,但其中大多数都已经过时了。

那么有没有办法做到这一点? 目前,我在浏览器(我们使用 Chrome)上运行的代码如下所示:

api({
  url: url,
  method: 'GET',
  responseType: 'blob',
}).then((response) => {

  const blob = new Blob([response.data], {type: response.data.type})
  const url = window.URL.createObjectURL(blob)
  let fileName = extractFilename(response)

  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  link.remove()
  window.URL.revokeObjectURL(url)
})

【问题讨论】:

    标签: cordova vue.js download inappbrowser


    【解决方案1】:

    原因是下载文件需要文件系统访问,移动应用比桌面更严格。如此简单的下载属性不起作用。

    你需要安装cordova-plugin-file:https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/

    您可以按照那里的教程进行操作。如果有帮助,下面是我的示例代码:

    saveBlobToSystem(filename, blob) {
    
          // define the folder you want to save first, for example this is download folder in Android
    
          let folderpath = "file:///storage/emulated/0/download/";
    
          let vm = this;
          const onError = function(msg) {
            console.log("Error saving File to System");
          };
    
          window.resolveLocalFileSystemURL(folderpath, function(dir) {
            console.log("Access to the directory granted succesfully");
            dir.getFile(filename, { create: true }, function(file) {
              console.log("File created succesfully.");
              file.createWriter(function(fileWriter) {
                console.log("Writing content to file");
                fileWriter.write(blob);
                console.log("Successfully write file to system");
              }, onError);
            }, onError);
          }, onError);
        }

    然而,这个科尔多瓦插件可能无法在网页版上运行,所以我认为你仍然需要保留你的旧代码。您可以编写一个简单的 js 函数来检测用户平台(web 或 android 应用程序)并运行相应的函数。

    【讨论】:

    • 但是我应该把这个插件安装到 wrapper cordova 应用程序中,对吧?因为这段代码来自包装在cordova应用程序中的Vue.js应用程序,(InAppBrowser)无法访问包装器上下文。
    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 2014-03-23
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多