弹簧启动 Angular2 文件下载不起作用



我在使用 angular2 从弹簧启动加载文件时遇到问题。

这是我从弹簧启动的代码,它来自:使用弹簧MVC返回生成的pdf。我可以直接使用邮递员下载文件,但不能使用 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);
}

角度2服务

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

Spring 启动解决方案基于 Return 生成的 pdf 使用 spring MVC 和 PDF 上的 Angular2 Blob 不显示内容,Angular 2。有问题的代码完全有效。使用 pdf 文件自动关闭选项卡的原因是 chrome 中的广告拦截插件。

最新更新