Angular http get, download file from spring mvc server
I am using apache commons IOUtils copy method to send file from server to angularjs. This is my controller:
@RequestMapping(value="/download", method = RequestMethod.GET)
public void downloadFile(HttpServletResponse response) {
response.setContentType("image/jpg");
try {
File file = new File(filePath);
InputStream inputStream = new FileInputStream(file);
IOUtils.copy(inputStream, response.getOutputStream());
} catch (...) {
.......
}
In angularJs controller:
$http({
method: 'GET',
url: '.../download',
headers: {'Content-Type': 'image/jpg'}
})
.success(function(data, status){
console.log(data);
var blob = new Blob([data], {type: 'image/jpg'});
saveAs(blob, 'test.jpg');
})
.error(function(data, status){
....
})
When I upload a file on the client side, I cannot read it. When I open it with notepad ++, I find that the special characters have changed.
For example, when I open the source file with Notpad ++, I get this line: òŽsCJVäl · ²HWƒ ...; ¹ (OE $ Öö "A" { S€~
9ÎsŠÒogk
This same line, when I open the downloaded file using notepad ++, becomes: sCJVlHW; ($ Ӂҫ { S ~
9sogk
However, when I put the download link (localhost / myApplication / download) directly into the browser, it works correctly. The files need to be encrypted and authorization is needed to download the file, so I need to use angular HTTP get.
Any help would be greatly appreciated.
source to share
I had to add responseType to the HTTP request request:
$http({
method: 'GET',
url: '.../download',
responseType: 'arraybuffer'
})
.success(function(data, status){
console.log(data);
var blob = new Blob([data], {type: 'image/jpg'});
saveAs(blob, 'test.jpg');
})
.error(function(data, status){
....
})
Now it works.
source to share