后端返回stream数据流前端保存文件

1
2
3
4
5
6
7
8
9
10
11
// 指定responseType: 'blob'

const data = _
const url = window.URL.createObjectURL(new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'excel.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)

前端base64转换成二进制

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
const base64ToBlob = (code: any) => {
let parts = code.split(';base64,');
let contentType = parts[0].split(':')[1];
let raw = window.atob(parts[1]);
let rawLength = raw.length;
let uInt8Array = new Uint8Array(rawLength);
for(let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
};

/**
* 二进制转换之后通过点击将图片文件下载到本地
*/
let blob = base64ToBlob(bmwConf.photoB64);
let url = window.URL.createObjectURL(new Blob([blob], {type: "image/png"}))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'test.png')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)

封装一下:

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
function downloadFile(content, fileName) { //下载base64图片
var base64ToBlob = function(code) {
let parts = code.split(';base64,');
let contentType = parts[0].split(':')[1];
let raw = window.atob(parts[1]);
let rawLength = raw.length;
let uInt8Array = new Uint8Array(rawLength);
for(let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
};
let aLink = document.createElement('a');
let blob = base64ToBlob(content); //new Blob([content]);
let evt = document.createEvent("HTMLEvents");
evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为
aLink.download = fileName;
aLink.href = URL.createObjectURL(blob);
aLink.click();
};

// 使用
downloadFile('图片名称', 'data:image/png;base64,iVBORw0KGg....');