Spring Boot Angular2文件下载不起作用 [英] Spring boot Angular2 file download not working

查看:23
本文介绍了Spring Boot Angular2文件下载不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从角度为2的Spring Boot下载文件时遇到问题。

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

@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

推荐答案

SpringBoot解决方案基于Return generated pdf using spring MVCPDF Blob is not showing content, Angular 2上的Angular2。有问题的代码正在完全正常工作。使用pdf文件自动关闭选项卡的原因是Chrome中的广告块插件。

这篇关于Spring Boot Angular2文件下载不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆