【问题标题】:Cordova / Ionic - Download file from InAppBrowserCordova / Ionic - 从 InAppBrowser 下载文件
【发布时间】:2021-05-27 10:48:20
【问题描述】:

场景是这样的:我在InAppBrowser中打开一个网站,用户结束那里的工作后,网站生成一个.pdf供用户下载,问题是pdf没有下载,它打开它在浏览器中。

有没有办法让它从 InAppBrowser 下载?我目前正在开发一个 iOS 应用程序,因此该解决方案更适合 iOS。

提前致谢。

【问题讨论】:

  • 如果用户被重定向到 .pdf 文件或与用户工作时不同的 url,则可以使用 loadstart 事件来检测 .pdf 的 url 和然后使用文件传输插件下载,或使用带有 _system 选项的 inAppBrowser 将打开 safari,safari 将显示“打开方式”消息,用户可以使用任何支持 pdf 文件的应用程序打开 pdf
  • 网站提供了一个下载 .pdf 文件的按钮,当用户触摸该按钮时,pdf 将在 InAppBrowser 中打开。我会尝试添加loadstart 事件解决方案并回复您。我想如果它有效,我还必须处理查看 pdf 的窗口。谢谢你的建议。
  • 如果您在 loadstart 上检测到 pdf url,那么您可以使用 ref.close();开始下载后关闭 inAppBrowser 窗口

标签: ios cordova inappbrowser


【解决方案1】:

按照@jcesarmobile 的建议,这是我想出的:

首先我必须安装cordova-plugin-file-transfer

打开网址

var url = "http://mi-fancy-url.com";
var windowref = window.open(url, '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');

windowref 上为 loadstart 事件创建一个侦听器,并检查正在加载的内容是否为 pdf(这是我的情况)。

windowref.addEventListener('loadstart', function(e) {
  var url = e.url;
  var extension = url.substr(url.length - 4);
  if (extension == '.pdf') {
    var targetPath = cordova.file.documentsDirectory + "receipt.pdf";
    var options = {};
    var args = {
      url: url,
      targetPath: targetPath,
      options: options
    };
    windowref.close(); // close window or you get exception
    document.addEventListener('deviceready', function () {
      setTimeout(function() {
        downloadReceipt(args); // call the function which will download the file 1s after the window is closed, just in case..
      }, 1000);
    });
  }
});

创建处理文件下载的函数,然后打开它:

function downloadReceipt(args) {
  var fileTransfer = new FileTransfer();
  var uri = encodeURI(args.url);

  fileTransfer.download(
    uri, // file's uri
    args.targetPath, // where will be saved
    function(entry) {
      console.log("download complete: " + entry.toURL());
      window.open(entry.toURL(), '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');
    },
    function(error) {
      console.log("download error source " + error.source);
      console.log("download error target " + error.target);
      console.log("upload error code" + error.code);
    },
    true,
    args.options
  );
}

我现在面临的问题是它的下载路径,我只是无法打开它。但是,至少文件现在已下载。我将不得不创建一个 localStorage 项来保存不同文件的路径。

此步骤中缺少许多验证,这只是我快速制作的一个示例,以检查它是否有效。需要进一步验证。

【讨论】:

  • @João Pimentel Ferreira 为什么编辑将 $timeout 更改为 setTimeout? $timeout 是一个 angularjs 服务,是 setTimeout fn 的包装器,但在 angularjs 的范围内运行。
  • 啊好吧,这是因为这在纯 Cordova 中不可用,而 setTimeout 是普通的 Javascript
  • 是的,但这不适用于 vanilla js,它适用于使用 angularjs 的 ionic1,因此使用 $timeout 而不是 setTimeout :)
  • ok,但是ionic是基于Cordova的,cordova中有很多项目没有用到ionic
【解决方案2】:
  1. 使用 IAB 插件打开窗口并添加事件侦听器 ref = window.open(url, "_blank"); ref.addEventListener('loadstop', loadStopCallBack);

  2. 在 InAppBrowser 窗口中使用 https://xxx.pdf">documentName

  3. 调用操作
  4. 实现 loadStopCallBack 函数

    function loadStopCallBack(refTemp) {
        if(refTemp.url.includes('downloadDoc')) {
            rtaParam = getURLParams('downloadDoc', refTemp.url);
    
            if(rtaParam != null)
                downloadFileFromServer(rtaParam);
            return;
        }
    }
    
    function getURLParams( name, url ) {
        try {
            if (!url)
                url = location.href;
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(url);
            return results == null ? null : results[1];
        } catch (e) {
            showSMS(e);
            return null;
        }
    }
    

创建下载方法后

function downloadFileFromServer(fileServerURL){
try {
    var Downloader = window.plugins.Downloader;
    var fileName = fileServerURL.substring(fileServerURL.lastIndexOf("/") + 1);

    var downloadSuccessCallback = function(result) {
          console.log(result.path); 

    };

    var downloadErrorCallback = function(error) {
        // error: string
        console.log(error);
    };

    //TODO cordova.file.documentsDirectory for iOS

    var options = {
        title: 'Descarga de '+ fileName, // Download Notification Title
        url: fileServerURL, // File Url
        path: fileName, // The File Name with extension
        description: 'La descarga del archivo esta lista', // Download description Notification String
        visible: true, // This download is visible and shows in the notifications while in progress and after completion.
        folder: "Download" // Folder to save the downloaded file, if not exist it will be created
    };

    Downloader.download(options, downloadSuccessCallback, downloadErrorCallback);
} catch (e) {
    console.log(e);
}

}

你可以在这里获取插件https://github.com/ogarzonm85/cordova-plugin-downloader

它的工作原理太简单了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 2021-07-02
    • 2016-10-09
    • 1970-01-01
    相关资源
    最近更新 更多