Reputation: 27
I am working on file download where my front end is AngularJS and backend a spring controller
downloadResponse.success(function(response){
console.log(JSON.stringify(response));
var file = new Blob([ response ], {
type : 'application/octet-stream',
});
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = fileName;
document.body.appendChild(a);
a.click();
}).error(function(response){
console.log("Error");
});
};
Call to the Spring Controller
downloadFile:function(loggedId, fileId, fileName){
var downloadFileURL = "/downloadFile";
var formData = $.param({ "loggedId" : loggedId, "fileId" : fileId, "fileName": fileName});
return $http.post(downloadFileURL,formData, {headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}}, {responseType:"arraybuffer"});
}
Spring Controller
@RequestMapping(value = "/downloadFile")
public void downloadFile(@RequestBody String msgBody, @RequestParam(value = "loggedId") String loggedId, @RequestParam(value = "fileId") String fileId, @RequestParam("fileName") String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception {
byte[] bytes = downloadFile(loggedId, fileId, fileName, request, response);
response.setContentType("application/octet-stream; charset=UTF-8");
response.setContentLength(bytes.length);
response.getOutputStream().write(bytes);
/* InputStream in = new ByteArrayInputStream(bytes);
FileOutputStream fos = new FileOutputStream(filePath);
IOUtils.copy(in, fos); */ ---- I am able to download the file from the Spring controller
}
I am able to download the file with contents from Spring Controller but facing issues while passing it to angular. I am getting a empty pdf file. Text files are downloaded properly. Any help is greatly appreciated.
EDIT 1 : I can see something like this in the browser Response but not sure why an empty file is created
%PDF-1.4
%����
612 0 obj
<</Linearized 1
/L 979975
/H [ 10681 506 ]
/O 614
/E 149424
/N 60
/T 967590
>>
endobj
xref
612 497
0000000015 00000 n
0000010395 00000 n
0000011187 00000 n
0000011411 00000 n
0000011562 00000 n
0000011779 00000 n
0000011928 00000 n
0000012154 00000 n
0000012389 00000 n
0000012523 00000 n
0000012760 00000 n
0000012941 00000 n
0000013123 00000 n
0000013353 00000 n
Upvotes: 1
Views: 509
Reputation: 2189
Maybe angular don't trust your file. Please try to inject $sce (https://docs.angularjs.org/api/ng/service/$sce) into your angular controller and then call
url = $sce.trustAsResourceUrl(url)
on your url before you write it into a.href.
And i think the pdf content is available in response.data and not response itself.
var file = new Blob(response.data, {
type : 'application/octet-stream',
});
Upvotes: 1