【问题标题】:Blob type open more than one file type like pdf and jpegBlob 类型打开多种文件类型,例如 pdf 和 jpeg
【发布时间】:2020-06-30 08:28:20
【问题描述】:

我想通过单击我之前上传的文件在另一个浏览器选项卡中预览文件。 {type:'application/pdf'}{type: 'image/jpeg'} 可以正常工作,但我需要它们。

有没有办法为 Blob 设置多个类型? 当我从后端获取文档时,我不知道文件的类型。所以我无法检查文件是 pdf 还是 jpeg。

 const fileOpen = new Blob([response], {type: 'image/jpeg' }); // this works fine!! but i need to open a pdf file as well.

 const fileUrl = URL.createObjectURL(fileOpen);
 window.open(fileUrl);

【问题讨论】:

  • 你能根据响应确定文件类型吗? response 来自哪里?
  • 来自我的订阅。所以我通过发送 id 从后端获取文档并获取响应。这适用于 pdf 或 jpeg。但我需要打开pdf或jpeg。我不能给 blob 多个属性,或者我还不知道。这里是完整的部分: this.documentService.downloadDocument(document.id).subscribe( response => { const fileOpen = new Blob([response], {type: 'image/jpeg'}); const fileUrl = URL.createObjectURL( fileOpen ); window.open(fileUrl); )};
  • Blob 不关心 mime 类型,它只是贴在二进制内容上的各种“标签”,它对 Blob 创建是否成功没有任何影响- 所以你不能在那个地方做任何“试错”。您将需要找到一种方法来访问您的服务器随响应返回的 Content-Type(如果它首先这样做),或者您将不得不查看响应数据中的前几个字节,并冒险基于此的有根据的猜测。

标签: javascript typescript blob imagejpeg createobjecturl


【解决方案1】:

如果response是Fetch API Response对象,可以根据响应的类型设置Blob的类型:

const fileOpen = new Blob([response], {type: response.data.type });

const fileUrl = URL.createObjectURL(fileOpen);
window.open(fileUrl);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 2019-12-30
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    相关资源
    最近更新 更多