如何使用Spring进行POST请求下载文件?

3

使用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)

1
当您将其更改为POST时,它无法正常工作吗?您所需要的就是将响应头设置为文件。您可以在此处找到灵感:https://dev59.com/l2Qn5IYBdhLWcg3wrouL - Hrabosch
“POST”是一种用于提交数据而不是接收数据的方法,因此我认为使用“POST”来下载文件并不是一个好主意。 - noname
我同意你的看法,@noname。 - Bhaumik Thakkar
2个回答

0

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

'Content-type': 'application/json'

问题似乎已经解决了。


0
以下是我的示例工作代码,我正在使用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也可以正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接