【问题标题】:AngularJS open PDF in new tab and change filename/urlAngularJS 在新选项卡中打开 PDF 并更改文件名/url
【发布时间】:2017-02-01 02:19:27
【问题描述】:

在我的 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-Title 会正确显示。但是没有内容,文档是空的。

任何有关如何更改文件名和/或 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-Service

@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');
  • 谢谢@DanielBornstrand,这行得通。窗口标题现在只是document,但文档标题(如果文档被下载)是我指定的。这不是 100% 完美,但比以前更好,代码也更少:)
  • 我会发布它作为答案! :)

标签: javascript angularjs spring-mvc


【解决方案1】:

使用返回字节数组的资源的 url 打开一个新选项卡!比如:

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

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 2017-09-18
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 2020-10-09
    • 2018-11-28
    • 1970-01-01
    • 2016-07-13
    相关资源
    最近更新 更多