![](/img/trans.png)
[英]window.URL.createObjectURL set filename to open pdf in new tab
[英]AngularJS open PDF in new tab and change filename/url
在我的AngularJS网站中,我想加载.pdf文档并在新的浏览器标签中显示它们。 以下代码可以正常工作,但是有些事情困扰着我:
createdObjectURL设置为文档和浏览器选项卡的标题。 这意味着我的文档总是以诸如01d9bdca-9af2-43f0-a83f-f36fd82fd72
类的标题命名,这并不是很不错。 而且可见的URL也不是很好。 代替blob:http://localhost:8080/01d9bdca-9af2-43f0-a83f-f36fd82fd72f
,最好在service.js中使用我调用的URL。
我试图处理HttpHeaders中的文件名,但这完全没有效果:(
另一个奇怪的事情是:如果我未指定{responseType: "arraybuffer"}
,则会正确显示PDF标题。 但是没有内容,文档为空。
任何有关如何更改文件名和/或URL的帮助将不胜感激。 谢谢。
JS控制器
DocumentService.getDocument().then(function(response) {
$window.open(response, '_blank');
});
JS服务
return {
getDocument : function () {
return $http.get("document", {responseType: "arraybuffer"})
.then(function(response) {
var file = new Blob([response.data], {type: "application/pdf"});
var fileURL = URL.createObjectURL(file);
return fileURL;
}
}
}
Spring MVC ReST服务
@RequestMapping(value = "/document", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDocument(){
try {
File file = new File("C:\\pathToFile.pdf");
byte[] fileContent = new byte[(int) file.lenth()];
HttpHeaders heraders = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "NameOfFile.pdf";
headers.setContentDispositionFormData(filename, filename); //doesn't change anything
fileContent = File.readAllBytes(file.toPath());
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(fileContent, headers, HttpStatus.OK);
return response;
} catch (FileNotFoundException e ) {
System.err.println("File not found " + e);
} catch (IOException e ) {
System.err.pringln("Error while reading file " + e);
}
}
简短版本:将PDF文件作为字节数组加载并使用AngularJS $ window指令在新的浏览器选项卡中显示时:是否有可能更改文件名和URL?
打开一个新选项卡,其中包含指向返回字节数组的资源的URL! 就像是:
$window.open('localhost:xxx/api/document', '_blank');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.