简体   繁体   中英

Angular 7 pdf display file from blob

I'm returning a FileContentResult from my c# .NET API, in my angular 7 application I receive it as a blob with HttpClient and then use the following to open a new tab and try to display it.

this.myService.GetPdfBlob().subscribe(data => {
   var fileURL = window.URL.createObjectURL(data);
   window.open(fileURL, '_blank');
})

After doing this it opens up a new tab, but I see a huge json object's text where it starts with FileContents property and that value is a massive string that I imagine is the bytes of the pdf document. It looks kind of like this:

{"FileContents":"JVBERi0xLjUNJeLjz9MNCjI1IDAgb2JqDTw8L0xpbmVhcml6ZWQgMS9MIDg1NzU1L08gMjcvRSA3MzgzMy9OIDQvVCA4NTQxNS9IIFsgNDc5IDIyMl0+Pg1lbmRvYmoNICAgICAgICAgICAgICAgICAgDQozOCAwIG9iag08PC9EZWNvZGVQYXJtczw8L0NvbHVtb...it keeps going..", "FileDownloadName":"MyBigFile.pdf"}

How do I make it display the actual pdf document and not this big JSON object of my FileContentResult? I eventually need to display multiple file types, but I'm just starting with pdf.

I changed up my C# code slightly to return an object that has a bytes array byte[] called Bytes and a filename. I still had the problem until I did this in my angular code:

this.http.get(myUrl).subscribe(response => {
   var byteCharacters = atob(response.Bytes);
   var byteNumbers = new Array(byteCharacters.length);
   for (var i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i);
   }
   var byteArray = new Uint8Array(byteNumbers);
   var blob = new Blob([byteArray], {type: "application/pdf"});
   var fileURL = URL.createObjectURL(blob);
   window.open(fileURL, '_blank');
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM