【问题标题】:Spring boot Angular2 file download not workingSpring Boot Angular2文件下载不起作用
【发布时间】:2017-08-19 23:29:25
【问题描述】:

我在使用 angular2 从 Spring Boot 下载文件时遇到问题。

这是我的 Spring Boot 代码,来自:Return generated pdf using spring MVC。我可以用邮递员直接下载文件,但不能用 angular2...

@RequestMapping(value="/file/{id}", method=RequestMethod.GET)
public ResponseEntity<?> getFile(@PathVariable("id") long id) {
    UploadFile uFile = uploadFileService.getUploadFileById(id);


    byte[] contents = uFile.getContent();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    headers.setContentDispositionFormData(uFile.getName(), uFile.getName());
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

    return new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
}

Angular2 服务

downloadFile( id: number ){
    let headers = new Headers({'Content-Type': 'application/pdf', 'Accept': 'application/pdf'});
    headers.append('Authorization',this.auth.token);
    let options = new RequestOptions( { headers: headers, responseType: ResponseContentType.Blob});

    return this.http.get(this.editUrl + id, options)
    .map(res => {return new Blob([res.blob()],{ type: 'application/pdf' })});
}

还有下载按钮

downloadFile(uFile: UploadFile){
    this.uploadFileService.downloadFile(uFile.id)
        .subscribe(
                data => window.open(URL.createObjectURL(data)),
            );
    return false;
}

当我单击下载按钮时,chrome 会打开新标签并立即关闭它而不显示任何文件。 以下是邮递员的一些响应标头。

Access-Control-Allow-Headers →Content-Type, x-requested-with, Authorization, responseType
Access-Control-Allow-Methods →POST, PUT, GET, PATCH, OPTIONS, DELETE
Access-Control-Allow-Origin →http://localhost:4200
Access-Control-Max-Age →3600
Cache-Control →must-revalidate, post-check=0, pre-check=0
Content-Disposition →form-data; name="reference.pdf"; filename="reference.pdf"
Content-Length →31576
Content-Type →application/pdf
Date →Mon, 27 Mar 2017 08:39:24 GMT
X-Content-Type-Options →nosniff
X-Frame-Options →DENY
X-XSS-Protection →1; mode=block

【问题讨论】:

  • 是的,这些正是我在解决方案中使用的代码,但问题仍然存在。当我尝试在 IE 中下载文件时,它会打开新标签页,其中包含类似以下内容的链接:blob:8ASDA017-7456B-4614-AD56-47456456021
  • 它在 IE 中不起作用,据我所知仅在 Chrome 和 Mozilla 中起作用。
  • Chrome 100% 运行,尝试更新到最新版本。
  • 是的,我找到了解决问题的方法。 Adblock 插件被阻止了.....

标签: spring rest angular spring-boot multipartform-data


【解决方案1】:

Spring boot 解决方案基于Return generated pdf using spring MVCPDF Blob is not showing content, Angular 2 上的Angular2。有问题的代码完全可以工作。 pdf文件自动关闭标签的原因是chrome中的Adblock插件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 2017-01-31
    • 2019-10-30
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    相关资源
    最近更新 更多