js下载文件方法总结

通过blob流下载文件并重命名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import axios from "axios";
import fileDownload from "js-file-download";
import moment from 'moment'
/**
* 下载文件
* @param url {String} 文件地址
* @param title {String} 文件名
* @returns {Promise<Boolean>}
*/
const uDownloadFile = (url, title) => {
return new Promise((resolve, reject) => {
if (!url) {
reject(false)
}
if (url.indexOf('http') < 0) {
url = `${location.protocol}//xxx.xxx.com/${url}`;
}
let ext = url.match(/\.([0-9a-z]+)(?:[\?#]|$)/i)[0];
let filename = '';
if (!title) {
filename = `${moment().format('YYYY年MM月DD日 HH点mm分')}${ext}`;
} else {
// 替换掉windows系统文件名禁止的字符
title = title.replace(/\?|\/|\\|<|>|\||"|\*/g, '_');
filename = `${title}${ext}`
}
axios({
method: 'get',
url: url,
responseType: 'blob',
}).then(res => {
fileDownload(res.data, filename);
resolve(true)
}).catch(err => {
resolve(true)
});
})
}

export {uDownloadFile}