我正在使用 apache commons IOUtils 复制方法将文件从服务器发送到 angularjs。 这是我的 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 (...) {
.......
}
在 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){
....
})
当我在客户端下载文件时,我无法读取它。当我用notepad++打开它时,我发现特殊字符被修改了。
例如,当我用 Notpad++ 打开原始文件时,我得到这样一行:
òŽsCJVäl·²HWf…;¹(òÈ$ÓÒ«Á´{S€~
9ÎsŠÒogk
同一行,当我用 Notepad++ 打开下载的文件时变成:
��sCJV�l��HW��;�(��$�ׁ����{S�~
9�s�ogk
但是,当我将下载链接(localhost/myApplication/download)直接放入浏览器中时,它可以正常工作。文件应该被加密并且下载文件需要授权,所以我必须使用 Angular HTTP get。
如有任何帮助,我们将不胜感激。
最佳答案
我必须将responseType 添加到HTTP get 请求:
$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){
....
})
现在它正在工作。
关于angularjs - Angular http get,从 spring mvc 服务器下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31690293/