web下载附件及修改名称

 1 /**
 2  * @param: url 附件地址
 3  * @param: filename 下载后的文件名
 4  */
 5 function download(url, filename) {
 6     getBlob(url, function (blob) {
 7         saveAs(blob, filename);
 8     });
 9 
10 }
11 
12 function getBlob(url, cb) {
13 
14     var xhr = new XMLHttpRequest();
15 
16     xhr.open('GET', url, true);
17 
18     xhr.responseType = 'blob';
19 
20     xhr.onload = function () {
21 
22         if (xhr.status === 200) {
23 
24             cb(xhr.response);
25 
26         }
27 
28     };
29 
30     xhr.send();
31 
32 }
33 
34 function saveAs(blob, filename) {
35 
36     if (window.navigator.msSaveOrOpenBlob) {
37 
38         navigator.msSaveBlob(blob, filename);
39 
40     } else {
41 
42         var link = document.createElement('a');
43 
44         var body = document.querySelector('body');
45 
46         link.href = window.URL.createObjectURL(blob);
47 
48         link.download = filename;
49 
50         // fix Firefox
51 
52         link.style.display = 'none';
53 
54         body.appendChild(link);
55 
56         link.click();
57 
58         body.removeChild(link);
59 
60         window.URL.revokeObjectURL(link.href);
61 
62     };
63 
64 }

 

posted @ 2019-11-14 14:11  python_yue  阅读(641)  评论(1编辑  收藏  举报