为什么我返回图片给前端还是乱码
这是为什么呢,我的content-type是JPEG啊
后端这么写没问题,是对的
前端接收到的是文档流的形式,需要规定ajax以blob形式接收,然后下载
https://blog.csdn.net/m0_37687058/article/details/124177135
https://zhuanlan.zhihu.com/p/502721718
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="downloadImage()">下载图片</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function downloadImage() {
const imageName = '1.png' // 下载图片名称
$.ajax({
url: 'http://localhost:3000/public/img/' + imageName,
type: 'GET',
xhrFields: {
responseType: 'blob' // 规定以blob形式接收
},
success: (res) => {
const a = document.createElement('a');
const blob = new Blob([res]);
const href = window.URL.createObjectURL(blob);
a.href = href;
a.download = imageName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(href);
}
})
}
</script>
</body>
</html>