0

I want to preview a file in another browser tab by clicking on a file which I uploaded before. It's working fine with {type:'application/pdf'} or {type: 'image/jpeg'} but I need both of them.

Is there a way to set more than one type for a Blob? When i get the Dokument from the Backend I don't geht the type of the file. So I can't check either a File is pdf or a 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);
Hakan Dilek
  • 2,178
  • 2
  • 23
  • 35
melodi
  • 1
  • 2
  • Can you determine the file type based on the response? Where's `response` coming from? – apokryfos Jun 30 '20 at 08:34
  • from my subscribe. So i get the document from my backend by sending the id and get the rsponse. That is working fine with pdf or jpeg. But i need to open either pdf or jpeg. i cant give the blob multiple properties or i dont know yet. Here the ful piece: this.documentService.downloadDocument(document.id).subscribe( response => { const fileOpen = new Blob([response], {type: 'image/jpeg'}); const fileUrl = URL.createObjectURL(fileOpen ); window.open(fileUrl); )}; – melodi Jun 30 '20 at 09:36
  • The Blob doesn’t care about the mime type, that is just a “label” of sorts that gets slapped onto the binary content, it doesn’t have any influence on whether the Blob creation will succeed - so you can’t do any “trial&error” in that place. You will need to either find a way to access the Content-Type your server returned with the response (if it does that in the first place), or you will have to look at the first couple of bytes in your response data, and hazard an educated guess based on that. – CBroe Jun 30 '20 at 10:38

1 Answers1

0

If response is a Fetch API Response object, you can set the type of Blob according to the type of response:

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

const fileUrl = URL.createObjectURL(fileOpen);
window.open(fileUrl);
Ethan McTague
  • 2,236
  • 3
  • 21
  • 53