重现问题的步骤:
我正在使用服务将 Blob 对象保存为表单数据,并且收到内容类型为 application/octet-stream 的响应,如附图所示
预期结果是什么?
- 将应用程序/八位字节流作为图像下载并查看到本地计算机,并使用应用程序查看它
会发生什么?
能够将文件下载为图像,但它说我们不支持这种文件格式(例如:image.png)
function add() {
$.ajax({
url: 'https://localhost:3000/upload/sampleImage.png',
type: 'GET',
success: function (data) {
const link = document.createElement('a');
link.style.display = 'none';
link.download = "sample image";
link.href =
'data:' +
'image/png' +
';base64,' +
window.btoa(unescape(encodeURIComponent(data)));
link.click();
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}
});
}
有什么方法可以下载文件并成功预览
最佳答案
在请求中将responseType设置为blob
使用 HttpClient:
this.http.get("https://localhost:3000/upload/sampleImage.png",{responseType:'blob'}).subscribe((img)=>{
const link = document.createElement('a');
link.style.display = 'none';
link.download = "sample image";
link.href =window.URL.createObjectURL(data);
link.click();
});
现在使用 $.ajax(不推荐,避免使用它)指定 dataType 为 blob 并使用 window.URL.createObjectURL(data)
创建 URL
$.ajax({
url: 'https://localhost:3000/upload/sampleImage.png',
type: 'GET',
xhrFields:{
responseType: 'blob'
},
success: function (data) {
const link = document.createElement('a');
link.style.display = 'none';
link.download = "sample image";
var blob = new Blob([data], {type: 'image/png'});
link.href =window.URL.createObjectURL(blob);
link.click();
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}
关于javascript - 下载作为二进制/八位字节流的 PNG 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60915291/