我有一个适用于 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' });
}
};
});
现在在 Controller 中我所要做的就是调用服务并打开一个包含 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');
});
};
希望它能帮助别人!
最佳答案
如果您从网络服务器提供 Angular 部分,则无法访问服务器的文件系统。这将是一个严重的安全问题。
为什么不提供另一个 @RequestMapping(value = "/getFile")
来直接向用户提供文件,并使用正确的 MIME 类型?
这是一个类似的问题Return generated pdf using spring MVC以及如何做到这一点的答案。
关于java - 在 angularJS 中下载本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29683320/