2016-09-23 36 views
0

在我的AngularJS网站中,我想加载.pdf文档并在新的浏览器选项卡中显示它们。下面的代码可以工作,但有些东西会打扰我:AngularJS在新选项卡中打开PDF并更改文件名/ URL

createdObjectURL被设置为文档和浏览器选项卡的标题。这意味着我的文档总是被标题为01d9bdca-9af2-43f0-a83f-f36fd82fd72,这不太合适。可见的URL也不好。而不是blob:http://localhost:8080/01d9bdca-9af2-43f0-a83f-f36fd82fd72f最好是在service.js中调用我所调用的URL。

我试图以处理HttpHeaders文件名,但没有任何效果可言:(

另一个奇怪的事情:如果我不指定{responseType: "arraybuffer"},正确显示PDF格式的标题,但没有。没有内容,该文件是空的。

如何更改文件名和/或网址,将不胜感激任何帮助,谢谢。

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?

+1

难道你不能只打开一个新的选项卡与url的资源返回字节数组?就像'$ window.open('localhost:xxx/api/document','_blank');' – Amygdaloideum

+0

谢谢@DanielBornstrand,这个工程。窗口标题现在只是“文档”,但文档标题(如果文档被下载)是我指定的标题。这不是100%完美,但比以前更好,也更少的代码:) – Freddy

+0

我将它作为答案张贴! :) – Amygdaloideum

回答

3

打开一个新的选项卡,其URL返回字节数组的资源!就像:

$window.open('localhost:xxx/api/document', '_blank');