文件下载时文件名乱码
解决方案:
Java代码设置URLEncoder.encode(filesName,StandardCharsets.UTF_8.name()),设置成new String(filesName.getBytes("utf-8","ISO-8559_1"))无效
String filesName=s.substring(s.lastIndexOf("/") + 1);
response.setContentType(MediaType.MULTIPART_FORM_DATA_VALUE);
response.setContentType(StandardCharsets.UTF_8.name());
//防止中文乱码
response.setHeader("Content-disposition",
"attachment;filename="+ URLEncoder.encode(filesName,StandardCharset s.UTF_8.name()));
前端设置解码decodeURI(fileName);
$.ajax({
url: "${ctx}/template/uploadLatterTemleaf",
type: "POST",
data: {"list": list},
xhrFields: {
responseType: "arraybuffer"
},
success: function (res,_,xhr) {
let content = xhr.getResponseHeader('content-disposition');
let fileName = content.split(";")[1].split("filename=")[1];
// const fileName = decodeURI(res.headers.get('content-disposition')).split('filename=')[1]
let blob = new Blob([res], {
type: "application/octet-stream",
});
let link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = decodeURI(fileName);
// link.download = '授权委托书-诉讼'
link.click();
window.URL.revokeObjectURL(link.href);
},
error: function (err) {
console.log(err)
}
})