【发布时间】:2015-06-23 08:49:00
【问题描述】:
我有一个适用于 Java 和 AngularJS 的应用程序。
我用 Java 创建 pdf 文件,使用 FileOutputStream 来存储它们:
@RequestMapping(value = "/getPdf",
method = RequestMethod.GET)
@RolesAllowed(AuthoritiesConstants.USER)
public List<String> getPdf(@RequestParam(value = "id") Long id){
FileOutputStream fileStream = null;
String fileName = textRepository.findOne(id).getTitle() + ".pdf";
String text = textRepository.findOne(id).getUserText();
try {
fileStream = new FileOutputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// create an API client instance
Client client = new Client("", "");
client.convertHtml(text, fileName);
try {
fileStream.close();
} catch (IOException e) {
e.printStackTrace();
}
List<String> out = new ArrayList<>();
out.add(fileName);
return out;
}
They are created in the root directory of my application.
现在我想实现一个功能,让用户通过单击链接或按钮下载 pdf。我已尝试使用$window.open(),但无法获取我的 pdf 文件的路径。
$scope.getPdf = function (id) {
TextService.getPdf(id).success(function(data){
$window.open('../../../../../../' + data[0], '_blank', 'download');
});
};
Here i get an error saying that Cannot GET /data.pdf
编辑 - 解决了问题
我必须执行一个发送文件的 POST 方法:
@RequestMapping(value = "/getPdf",
method = RequestMethod.POST)
@RolesAllowed(AuthoritiesConstants.USER)
public ResponseEntity<byte[]> getPdf(@RequestBody Long id){
String filename = textRepository.findOne(id).getTitle() + ".pdf";
String text = textRepository.findOne(id).getUserText();
ByteArrayOutputStream pdf = new ByteArrayOutputStream();
// create an API client instance
Client client = new Client("", "");
client.convertHtml(text, pdf);
byte[] content = pdf.toByteArray();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.setContentDispositionFormData("inline", filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(content, headers, HttpStatus.OK);
return response;
}
回到我的 AngularJS 客户端,我有一个调用 Java 方法的服务:
angular.module("eddieApp")
.factory("TextService", function($http){
return{
getPdf: function(id){
return $http.post('texts/getPdf', id, { responseType: 'arraybuffer' });
}
};
});
现在在控制器中,我所要做的就是调用服务并打开一个带有 pdf 的窗口:
$scope.getPdf = function (id) {
TextService.getPdf(id).success(function(data){
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = ($window.URL || $window.webkitURL).createObjectURL(file);
$window.open(fileURL, '_blank', 'download');
});
};
希望它对某人有所帮助!
【问题讨论】:
-
帮了我很多忙!谢谢。