【问题标题】:Angular Spring Boot File DownloadAngular Spring Boot 文件下载
【发布时间】:2020-06-12 13:08:02
【问题描述】:

祝您阅读本文愉快!

我在此软件设置中完成了上传功能,但我无法完成下载部分... 在这里尽可能多地挖掘,这就是我到目前为止的地方。

我的代码如下所示:

服务器

 @GetMapping(value = "/projects/file/download/{filename}/{projectId}")
 public ResponseEntity<byte[]> getResource(@PathVariable String filename, @PathVariable Long 
    projectId,HttpServletResponse response) throws ResourceNotFoundException, IOException {

    String fileLocation=//a location that I set, removed logic to make this shorter

    File downloadFile= new File(fileLocation);

    byte[] isr = Files.readAllBytes(downloadFile.toPath());
    String fileName = filename;
    HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentLength(isr.length);
    respHeaders.setContentType(new MediaType("text", "json"));
    respHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
    return new ResponseEntity<byte[]>(isr, respHeaders, HttpStatus.OK);

 }

角度服务

downloadFile(filename: string, projectId: number): Observable<any> {
 return this.http.get(`${this.baseUrl}/file/download/` + filename + '/' + projectId, { responseType: 'blob' });
}

角度组件

downloadFile(fl: FileModel) {
  //calling service
  this.projectSerivce.downloadFile(fl.fileName, this.id).subscribe(response => {
    window.open(response.url, '_blank');
  });
}

它到达服务器并返回,然后打开一个新的空白浏览器选项卡,没有其他任何反应.. 没有任何错误。

【问题讨论】:

  • @michaeak 试过了,我得到另一个错误:SyntaxError: Unexpected token P in JSON at position 0
  • 我修复了这个错误,但是当从服务器返回时,blob 是空的,并且 response.body 是未定义的

标签: angular spring-boot download


【解决方案1】:

试试这个,

弹簧控制器

@GetMapping(value = "/projects/file/download/{filename}/{projectId}")
public void getResource(@PathVariable String filename, @PathVariable Long 
    projectId,HttpServletResponse response) throws ResourceNotFoundException, IOException {

    String fileLocation=//a location that I set, removed logic to make this shorter

    File downloadFile= new File(fileLocation);

    byte[] isr = Files.readAllBytes(downloadFile.toPath());
    ByteArrayOutputStream out = new ByteArrayOutputStream(isr.length);
    out.write(isr, 0, isr.length);

    response.setContentType("application/pdf");
    // Use 'inline' for preview and 'attachement' for download in browser.
    response.addHeader("Content-Disposition", "inline; filename=" + fileName);

    OutputStream os;
    try {
        os = httpServletResponse.getOutputStream();
        out.writeTo(os);
        os.flush();
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    /*HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentLength(isr.length);
    respHeaders.setContentType(new MediaType("text", "json"));
    respHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
    return new ResponseEntity<byte[]>(isr, respHeaders, HttpStatus.OK);*/
}

角度服务

import { map } from "rxjs/operators";

downloadFile(filename: string, projectId: number): Observable<any> {
    return this.http.get(`${this.baseUrl}/file/download/` + filename + '/' + projectId, { responseType: 'blob' }).pipe(map((response)=>{
        return {
            filename: 'yourFileName.pdf',
            data: response.blob()
        };
    }));
}

角度组件

downloadFile(fl: FileModel) {

    //calling service
    this.projectSerivce.downloadFile(fl.fileName, this.id).subscribe(response => {

        console.log(response);
        var binaryData = [];
        binaryData.push(response.data);
        var url = window.URL.createObjectURL(new Blob(binaryData, {type: "application/pdf"}));
        var a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display: none');
        a.setAttribute('target', 'blank');
        a.href = url;
        a.download = response.filename;
        a.click();
        window.URL.revokeObjectURL(url);
        a.remove();

    }, error => {

        console.log(error);
    });
}

【讨论】:

  • 我试图让它以这种方式工作,但我收到一条错误消息:无法在“URL”上执行“createObjectURL”:找不到与提供的签名匹配的函数。
  • 我正在使用 Angular 8/这会改变吗?
  • 是的,对于不同的文件,您可以传递application/*
  • 我修复了 URL 问题,但文件未定义
  • 尝试在服务器上调试,确保你在isr.length上有一定的长度。
猜你喜欢
  • 2019-12-03
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-09
  • 1970-01-01
  • 2016-06-11
  • 1970-01-01
相关资源
最近更新 更多