Saving the PDF file returned by the service

I use FileSaver.js and Blob.js in an Angular JS application to save the PDF returned by the REST service (which returns an array of bytes representing the file).

var headers = {headers: {"Authorization":"Bearer "+token, "Accept":"application/pdf"}}; $http.get(URL, headers) .success(function (data) { var blob = new Blob([data], {type: 'application/pdf'}); saveAs(blob, 'contract.pdf'); }); 

the file is saved with the correct type, and the number of pages is correct, but it is completely empty. Opening it with an editor, it turned out that it contains only the first part of the data returned by the server, for example, truncated.

Thank you all for your help!

+6
source share
2 answers

$ http.get is probably processing binary data incorrectly. Try $http({method: "GET", url: URL, responseType: "arraybuffer", ...}) (see Angularjs) to get a binary that you can insert for the data.

You can also use responseType: "blob" , so you don’t even need to create var blob , but I think that responseType has less browser support.

+7
source

Adding a response type to the config argument worked for me. Try:

 var config = { responseType: 'blob', headers: {"Authorization":"Bearer "+token, "Accept":"application/pdf"}}; $http.get(URL, config) .success(function (data) { var blob = new Blob([data], {type: 'application/pdf'}); saveAs(blob, 'contract.pdf'); }); 
0
source

Source: https://habr.com/ru/post/977755/


All Articles