Angular Spring启动文件下载 [英] Angular Spring Boot File Download

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

问题描述

祝您阅读愉快!

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

I did the upload functionality on this software setup but I cannot finish the download part... Digged as much as I could around here and this is where I got so far.

我的代码如下:

服务器

 @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');
  });
}

它到达服务器并返回,然后打开一个新的空白浏览器选项卡,并且没有发生其他任何事情.

It reaches server and comes back and then a new blank browser tab is open and nothing else happens.. No error whatsoever.

推荐答案

尝试一下,

Spring Controller

@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);
    });
}

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

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