Reputation: 847
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.
Upvotes: 0
Views: 7222
Reputation: 847
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');
})
Upvotes: 2