window.open下载文件,是如何准确的获取到中文文件名的呢?
我在做一些很老旧的功能改造,项目中用到了很多window.open 下载文件的方式;由于我需要捕获且展示下载接口有可能返回的错误信息,所以我不再使用window.open下载,而是在ajax.get回调中处理;
回调中需要获得响应头中的Content-Disposition字段读取文件名【文件名包含中文】 ,但获取到的总是乱码,图如:
1、

2、

经过尝试,发现有部分filename 原来是gbk | utf-8编码,因为reponse Header 只能使用iso-8859-1的缘故,转成了不同的看似乱码的情况,得经过转换才能还原到原来的中文,操作:
// 默认原来以gbk方式解码
let codeType = 'gbk';
if(contentType === 'application/x-msdownload'){
codeType = 'utf-8'
}
const contentDisposition = xhr.getResponseHeader('Content-Disposition');
const filename = contentDisposition.split('filename=')[1].replace(/"/g, '');
// 将 ISO-8859-1 编码的 filename 转换回 GBK或者utf-8
const byteCharacters = new Uint8Array(filename.split('').map(c => c.charCodeAt(0)));
const decoder = new TextDecoder(codeType);
// 解码回中文的下载文件名
const decodedFilename = decoder.decode(byteCharacters);
// 下载文件
const blob = new Blob([xhr.response], { type: xhr.getResponseHeader('Content-type') });
const link = document.createElement('a');
// 使用 blob 作为 URL
link.href = window.URL.createObjectURL(blob);
// 设置下载文件名
link.download = window.decodeURIComponent(decodedFilename) || '导出文件';
link.click();
目前适配了系统多数文件的下载;但是不知道window.open是做了什么操作,下载的文件名称总能很好的转成对应的中文?我上面那种方案,有挺大的风险,假如原来的编码是utf-8,而我使用gbk 去decode的话就也会乱码。
请教各位,能否给一些资料参考或者建议,比如window.open之后浏览器的下载操作【浏览器层面是怎么识别到filename并转换为中文】,又比如当前是乱码的情况下,怎么判断经iso-8859-1转化前,原来的编码格式是gbk 还是 utf-8?