我正在尝试建立图像下载功能。我在下面的代码 angularJs控制器
$scope.download= function(){
smoothingFilterService.downloadImage($scope.imageObj.destinationPath).then( function (data, status, headers, config) {
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:application/jpg,' + data.data,
target: '_self',
download: data.headers.filename
});
angular.element(document.body).append(anchor);
anchor[0].click();
},function (error) {
})
}
Angular Service中的代码
downloadImage:function(filePath){
var req={
method:'GET',
url:'/iprocessor/downloadImage',
params: {filePath: filePath},
transformResponse: function (data, headers) {
var response = {};
response.data = data;
// take note of headers() call response.headers = headers();
return response;
}
}
return $http(req)
}
HTML代码
<a class=" small" href="" ng-click="download()">Download </a>
后端Java控制器代码
@RequestMapping(value="/downloadImage",method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<byte[]> downloadImage(@RequestParam String filePath, HttpServletResponse response) throws IOException {
response.setHeader("Content-disposition","attachment; filename=sharp.jpg");
File file= new File(filePath);
FileSystemResource fileResource = new FileSystemResource(file);
byte[] base64Bytes = Base64.encodeBase64(IOUtils.toByteArray(fileResource.getInputStream()));
HttpHeaders headers = new HttpHeaders();
headers.add("filename", fileResource.getFilename());
return ResponseEntity.ok().headers(headers).body(base64Bytes);
}
当我点击下载链接时,它将下载名称为“ download”的文件,没有任何扩展名。我本来希望文件“ sharp.jpg”。
Http请求调用