需求
在项目中遇到这样一个需求:修改下载.zip文件的文件名。
需要在".zip"前加userId(用户id)
xxx.zip ==> xxx_userId.zip
个人使用的是手写xhr修改文件名的方式,代码如下:
function download() {
let url = "xxx";
let xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (xhr.status == 200) {
let blob = xhr.response;
let href = window.URL.createObjectURL(blob);
//获取文件名
let filename = '';
let contentDisposition = xhr.getResponseHeader("Content-disposition").split('=')[1]; // 取文件名
console.log(contentDisposition);
contentDisposition = decodeURI(escape(contentDisposition));
let downloadElement = document.createElement('a');
downloadElement.href = href;
downloadElement.target = '_blank';
downloadElement.download = contentDisposition.split('.zip')[0] + '_' + userId + '.zip';
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
}
}
xhr.send();
看一下console.log(contentDisposition)打印出的值。
可以发现是乱码
解决方式参考了一篇文章,具体做法是decodeURI(escape(contentDisposition))。
reponseHeader 中文乱码问题https://blog.csdn.net/u012165930/article/details/52635768https://blog.csdn.net/u012165930/article/details/52635768最终就可以修改下载zip文件的名字了。
遗留问题
虽然成功修改了zip文件的名字,但是解压之后的excel文件名还是修改之前的。