javascript - 下载作为二进制/八位字节流的 PNG 文件

标签 javascript angular typescript blob content-type

enter image description here重现问题的步骤:

我正在使用服务将 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/

相关文章:

javascript - for..in 和 hasOwnProperty

javascript - Redux Mock Store 提供 'Actions must be plain objects. Use custom middleware for async actions.'

angular - 如何通过迭代 typescript 中的数组和标签中的组项目来填充菜单项?

Angular (5) httpclient observe 和 responseType : 'blob'

typescript - ngFormModel 的动态属性?

javascript - 自动完成 : first item focused only when the user type on tab key

javascript - jquery - 查找具有某些属性的第一个前一个节点

typescript - typescript 中函数的 ' : ' 和 ' => ' 有什么区别?

typescript - VeeValidate 附加方法 : A field is missing a "name" or "data-vv-name" attribute when fields do have name

javascript - typescript :找不到 namespace