0

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.

4
  • 1
    I think you'll be better off changing the api to return a MIME type of application/pdf with only the file bytes. Commented Nov 19, 2019 at 22:48
  • changing the c# contentType to 'application/pdf' did not change anything, it is still behaving the same giving me this object and displaying its string in a new tab Commented Nov 20, 2019 at 14:41
  • Since the problem is likely in the C# code you should post that Commented Nov 20, 2019 at 17:38
  • I got it working, I had to do some weird stuff in the angular code. There must be a better way, but this works. I'll answer the question with the code. Commented Nov 20, 2019 at 18:44

1 Answer 1

2

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');
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.