使用文件保护程序下载文件(angular4 / spring boot)

时间:2018-03-14 09:16:50

标签: java spring angular jwt

我正在处理一个项目,当我点击按钮时需要保存PDF文件,

 @RequestMapping(value = "/download/{filename}", method = RequestMethod.GET)
 public ResponseEntity<InputStreamResource> download(@PathVariable String filename) throws IOException{
     String fullPath=FILE_PATH+""+filename+".pdf";
     System.out.println(fullPath);
     File file =new File(fullPath);
     HttpHeaders respHeaders = new HttpHeaders();
     respHeaders.setContentType(MediaType.APPLICATION_PDF);
    respHeaders.add("Content-Disposition", "attachment; filename=" + filename);
    respHeaders.add("Accept","application/pdf");
     InputStreamResource isr = new InputStreamResource(new FileInputStream(file));

     return new ResponseEntity<InputStreamResource>(isr,respHeaders,HttpStatus.OK);

使用ARC测试它会显示类似这样的内容

testing my rest

和我的html

的角度
<button (click)="saveF(a)">Export</button></div>

我的组件 A =&#34; a.pdf&#34 ;;

saveF(fileName){

this.authService.saveFile(fileName)
  .subscribe(response=> {
    this.saveToFileSystem(response)
    },
    err=>{
    console.log(err);
      console.log("not ok")
    }
  )

}

调用函数

private saveToFileSystem(response){
const contentDispositionHeader: string =response.headers.get('Content-Disposition');
const parts:string[]=contentDispositionHeader.split('.');
const filename=parts[1].split('=')[1];
const blob =new Blob([response._body]);
saveAs(blob,filename);

}

最后我的服务

saveFile(fileName){if (this.jwtToken== null){
this.loadToken()}
return this.http.get('http://localhost:8080/download/'+fileName,{headers:new HttpHeaders({'Authorization':this.jwtToken})})}

}

在我的浏览器中我得到类似的东西,但它没有下载文件 enter image description here

1 个答案:

答案 0 :(得分:0)

@Daniomi ty的答案,现在它可以工作,我不得不添加responseType,这就是我改变它的方式

saveF(fileName) {

this.authService.saveFile(fileName)
  .subscribe(response => {
      const name =fileName;
      const blob = response;
      saveAs(blob,name);
    },
    err => {
      console.log(err);

      console.log("not ok")
    }
  )

}

并在我的服务中

saveFile(fileName) {
if (this.jwtToken == null) {
  this.loadToken()
}
// const options = new RequestOptions({responseType: ResponseContentType.Blob });
return this.http.get('http://localhost:8080/download/' + fileName, {
  headers: new HttpHeaders({'Authorization': this.jwtToken}), responseType: 'blob'
})

}