You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular使用http.post下载文件多出Unknown.html多余文件问题求助

问题根因
  • 你的Spring Boot接口返回响应时携带了Content-Disposition: attachment头,这个头会触发浏览器的自动下载机制;同时你在Angular的回调中又调用了FileSaver.saveAs()主动执行了一次文件保存操作,两次下载行为叠加就出现了多余文件。
  • 浏览器自动识别POST接口返回的二进制流时,无法匹配到正确的文件名和格式,所以默认生成了Unknown.html文件。
解决方案

二选一即可,推荐方案1改动量更小:

方案1:修改服务端代码

删除响应头中的Content-Disposition配置即可,前端已经通过FileSaver指定了保存的文件名,不需要浏览器触发自动下载。
修改后的Java接口代码片段:

@RequestMapping(method = RequestMethod.POST, path = "/downloadDocument")
public ResponseEntity<ByteArrayResource> downloadFile(@RequestBody IdType docId) {
    //id here refers to the filename
    ByteArrayOutputStream downloadInputStream = documentsService.downloadFile(docId.getId());
    org.springframework.core.io.ByteArrayResource ts = new ByteArrayResource(downloadInputStream.toByteArray());
    // 仅删除Content-Disposition头配置即可,其他逻辑不变
    return ResponseEntity.ok()
            .contentType(contentType(docId.getId()))
            .body(ts);
}

方案2:修改前端代码

保留服务端配置,放弃使用AJAX调用+FileSaver的方式,改为用表单提交的方式触发下载,不需要额外调用保存方法,只会产生一个服务端指定文件名的文件。注意该方案需要同步调整服务端接口的参数接收方式,把@RequestBody改为@RequestParam适配表单参数格式,改动量更大
修改后的Angular代码片段:

downloadDocument(doc: JDocument) {
  // 创建隐藏表单提交触发下载
  const form = document.createElement('form');
  form.method = 'POST';
  form.action = `${this.baseUrl}/documents/downloadDocument`;
  form.target = '_blank';
  // 构造请求参数
  const input = document.createElement('input');
  input.type = 'hidden';
  input.name = 'id';
  input.value = doc.projectId + "/" + doc.documentName;
  form.appendChild(input);
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
}

内容的提问来源于stack exchange,提问作者sanj vij

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 12:27:04