【问题标题】:Download a file using POST request with Spring?使用 Spring 的 POST 请求下载文件?
【发布时间】:2017-04-24 15:27:11
【问题描述】:

对于使用 Spring 下载文件,我使用的是 GET 方法。

@RequestMapping(value = "/exportar/{tipo}", method = RequestMethod.GET)
@ResponseBody
public void exportar(HttpServletResponse response,@PathVariable TipoEnum tipo) throws IOException{

File file = service.exportar(tipo);

response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName() + ".xls"));
        response.setContentType("application/ms-excel; charset=UTF-8"); 
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    }

如何使用 POST 来实现这一点?这可能吗?

@RequestMapping(value = "/exportar", method = RequestMethod.POST)

【问题讨论】:

  • 而且改成POST就不行了?您需要的只是将响应标头设置为文件。你可以在这里找到灵感:stackoverflow.com/questions/16652760/…
  • POST 是一种 POST 数据而不是接收数据的方法,所以我认为使用 POST 下载文件不是一个好主意。
  • 同意你@noname

标签: java spring spring-data


【解决方案1】:

我刚刚在 Insomnia REST 客户端中重现了这个错误。
一旦我添加了标题:

'Content-type': 'application/json'

问题似乎已经解决了。

【讨论】:

    【解决方案2】:

    以下是我的示例工作代码,我使用的是 ResponseEntity,也可以不使用它。

    @PostMapping("/document/{documentId}")
    @Timed
    public ResponseEntity<byte[]> getDocumentById(@Valid @PathVariable Long documentId, ) throws MalformedURLException {
            return ResponseEntity.ok().header("Content-Disposition", "attachment; filename=" + caseId.toString().concat("_Document.pdf")).body(superBillGenerator.generateSuperBill(caseId, type));
    }
    

    之前是一个 GET 调用,但也适用于 POST。

    【讨论】:

      猜你喜欢
      • 2012-11-11
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      相关资源
      最近更新 更多