javascript异步下载 Promise实现

一般下载都是直接打开一个链接就行。
var URL = 'XXXX';
window.open(URL)
其实这样会有些问题:
1. 浏览器禁止打开新窗口,导致无法下载

那么怎么解决呢?
这样:

1 <a href="http://somehost/somefile.zip" download="filename.zip">Download file</a>

 


注意download属性,它说明要下载,并且文件名:filename.zip

那么如何异步下载?
JS的代码:

 1 var myDownload = function(){};
 2 myDownload.prototype = {
 3      // 同步 下载,只是将上面的例子变为js罢了
 4     download: function( url, filename ){
 5         var a = document.createElement('a');
 6         a.href = url;
 7         a.download = filename;
 8         a.click();
 9     },
10 
11     // 根据blob对象来下载
12     downloadByBlob: function(blod,name){
13         console.log('blod',blod);
14         name = name || blod.name;
15         var fileURL = window.URL.createObjectURL(blod); // 转换为可访问的URL
16         this.download(fileURL, name); // 下载
17         window.URL.revokeObjectURL(fileURL); //下载后释放URL
18     },
19 
20     // 异步 data='name=mynam&age=20'
21     ajax:function(url,data,method,type,successFuc,errorFuc){
22         method = method || 'GET';
23         data = data || '';
24         type = type || 'blob';
25         var request = new XMLHttpRequest();
26         if (window.XMLHttpRequest){
27             request=new XMLHttpRequest();
28         }
29         else if (window.ActiveXObject){
30             request=new ActiveXObject("Microsoft.XMLHTTP");
31         }else{
32             return false;
33         }
34         request.open(method, url);
35         request.responseType = type;
36         // When the request loads, check whether it was successful
37         request.onload = function() {
38             if (request.status === 200) {
39                 if(successFuc){
40                     var filename = request.getResponseHeader('Content-Disposition');
41                     if(filename){
42                         var index = filename.indexOf('filename=');
43                         if(index!==-1){
44                             filename = filename.substring(index+9);
45                         }
46                     }
47                     successFuc(request.response,filename)
48                 }
49             } else {
50                 if(successFuc){
51                     successFuc(request.response)
52                 }
53             }
54         }
55         request.onerror = function(error) {
56         // Also deal with the case when the entire request fails to begin with
57         // This is probably a network error, so reject the promise with an appropriate message
58             if(errorFuc){
59                 errorFuc(error.response)
60             }
61         };
62         // Send the request
63         request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
64         request.send(data);
65     },
66 
67     // 异步下载 没有Promise
68     downloadAsync:function(url,name,data,method){
69         var self = this;
70         this.ajax(url,data,method,'blob',function(blob,filename){
71             self.downloadByBlob(blob,name||filename);
72         });
73     },
74 
75     // 异步下载 使用Promise
76     downloadPromise:function(url,name,data,method){
77         if(window.Promise){
78             var self = this;
79             return new Promise(function(resolve, reject) {
80                 console.log(this,'this');
81                 self.ajax(url,data,method,'blob',function(response,filename){
82                     resolve({
83                         data:response,
84                         filename:filename
85                     });
86                 },function(response,filename){
87                     reject({
88                         data:response,
89                         filename:filename
90                     });
91                 })
92             }).then(function(json){
93                 self.downloadByBlob(json.data,json.filename);
94             });;
95         }else{
96            self.downloadAsync(url,data,method);
97         }
98     }
99 }

 

PHP的代码:

1 ini_set('memory_limit', '64M');
2 $file="myLittleVader.jpg";
3 header('Content-Type:application/octet-stream');
4 header('Content-Disposition:attachment; filename='.$file); //设定文件名
5 header('Content-Length:'.filesize($file));
6 readfile($file);

 

HTML:

 1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <meta charset="utf-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
 6     <meta name="viewport" content="width=device-width">
 7 
 8     <title>异步下载 example</title>
 9   </head>
10 
11   <body>
12     <h1>异步下载 example</h1>
13     <a href="#" onclick='DownJs.downloadPromise("download.php")'>DownloadJs</a>
14   </body>
15 
16 <script type="text/javascript" src="./download.js"></script>
17   <script>
18   var DownJs = new myDownload();
19   </script>
20 </html>

 

一般使用download既可以了,可以直接:

1 DownJs.download(url)

 


参考:
https://segmentfault.com/a/1190000005863250
promise下载

posted @ 2017-08-26 18:09  XIAOLI的博客  阅读(1297)  评论(0编辑  收藏  举报