【问题标题】:Save as blob takes too long to download the file from given url另存为 blob 需要很长时间才能从给定的 url 下载文件
【发布时间】:2016-04-03 10:13:23
【问题描述】:

我编写了以下服务来保存来自给定 URL 的文件。

(function() {
    angular.module('SOME_APP')
        .service("downloadService", downloadService);

        function downloadService($http){

            var downloadFileFromUrl = downloadFileFromUrl;

            function downloadFileFromUrl(url){

                if(!url.length){
                    //TO-DO handle the error
                }

                else{
                    //find the file name and extension, to save it as:
                    var fileName;
                    for(var i=url.length; i>=0; i--){
                        if(url[i]=='/'){
                            fileName=url.slice(i+1, url.length);
                            console.log(fileName);
                            break;
                        }
                    }
                    $http({
                        url: url,
                        method: "GET",
                        responseType: 'arraybuffer'
                        }).success(function (data) {
                            var blob = new Blob([data], {type: '*/*'});
                            saveAs(blob, fileName);
                        }).error(function (data) {
                            console.log(data);
                            //TO-DO error handling
                    });
                }
            }

            return {
                    downloadFileFromUrl : downloadFileFromUrl
            }
        }
}());

当我调用服务时,服务首先下载文件,一旦下载完成,然后在浏览器中显示下载(进度为100%)。如何让它正常工作? (在浏览器中启动下载,并逐渐显示进度)

【问题讨论】:

  • 为什么不设置一个计时器?
  • 你不能同时拥有。您无法下载本机浏览器并获得进度通知。您需要设置一个常规 XmlHttpRequest 并添加一个进度监听器,或者找到一种方法来操作 $http 中的底层 XHR 对象以添加一个监听器。
  • 每次数据到来时你都在保存它,这不是最好的下载方式。最好为传入数据注册事件并知道何时完成事务。如果您希望它像下载一样简单,您可以提供指向标签 html 的链接并为其赋予下载属性。这只是为您下载它

标签: javascript angularjs download blob save-as


【解决方案1】:

我的目的是从给定的 url 下载文件。我使用带有下载属性的 HTML5 锚标记实现它:

在 index.html 中:

               <a id='downloadTag' href="" download hidden></a>

在服务中:

                document.getElementById("downloadTag").href=url;
                document.getElementById("downloadTag").click();

这解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    相关资源
    最近更新 更多