angular - 从 Angular 和 Spring MVC API 下载文件

标签 angular spring spring-mvc

我正在尝试通过单击 Angular 中的按钮来下载文件。文件已下载,但大小为 0 KB,无法打开。

这是我迄今为止在 Angular 和 Spring MVC 中使用的代码

Angular :

public downloadFile(fileName:string){
    console.log("ready to download");
    let param:any = {'messageId':this.loadedMessageService.messageId, 'attachmentName':fileName}
    this.http.get(`https://fakeurl.com/abc/getFile`,{params:param,responseType:'blob'}).subscribe(
      (data) => {
        let b:Blob = new Blob([data])
        //,{type: 'application/octet-stream',}
       // const fileName :string= "RL.xlsx" 
        var url = window.URL.createObjectURL(b);
        const a : HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;
       // const a = document.createElement('a');
        document.body.appendChild(a);
        a.href = url;
        a.download = fileName; 
        a.click();
        document.body.removeChild(a);
       URL.revokeObjectURL(url);
      }
    )
  }

Spring MVC:

@GetMapping(value = "/getFile")
     public @ResponseBody byte[] getFile() throws IOException {
           try {
                return messageAttachmentService.getFile(Integer.parseInt(request.getParameter("messageId")), request.getParameter("attachmentName"));
           } catch (NumberFormatException e) {
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                logger.error(sw.toString());
           } catch (Exception e) {
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                logger.error(sw.toString());
           }
           return null;
     }

现在,当我单击按钮时,文件会被下载,但大小为 0 KB 并且无法打开。我之前使用类型为 application/octet-stream,因为要下载的文件可以是 PDF、文本文件或 xls。 我也提到了其他问题,并尝试将响应类型更改为 arraybuffer。这也没有解决问题。我的代码有什么问题吗?

最佳答案

您可以尝试使用 file-saver包裹。它很容易使用。

从“file-saver”导入*作为FileSaver;

const blob: any = new Blob([data], { type: 'octet/stream' });
saveAs(blob, "hello world.txt");

关于angular - 从 Angular 和 Spring MVC API 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56124360/

相关文章:

angular - 使用 PrimeNG 的 Angular 2 typescript 日历

spring - 非法状态异常 : must not be null of Spock unit test with Kotlin business logic

java - Spring Boot 元空间内存泄漏

java - 在spring mvc应用中提交输入类型="date"

spring - 配置文件中的管理器 Spring MVC @RequestMapping

javascript - 由接口(interface)强制执行的异步方法的顺序调用,Angular 4

javascript - 如何在 Ionic2 提供程序上创建和使用模块类?

java - 用于枚举接口(interface)的 Spring @ResponseBody 和 Jackson JsonSerializer

angular - 如何获取 Angular ng-bootstrap 断点

java - spring boot RestController JSON序列化花费太多时间