从Spring Rest Controller下载文件

时间:2022-04-11 10:00:43

I am trying to download a file through Spring REST Controller. Below is my code -

我试图通过Spring REST Controller下载文件。以下是我的代码 -

@RequestMapping(value="/aaa",method=RequestMethod.GET,produces=MediaType.APPLICATION_OCTATE_STREAM_VALUE) 
public ResponseEntity<byte[]> testMethod(@RequestParam("test") String test) {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentDispositionFromData("attachment","testExcel.xlsx");
    responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    File file = new File("C:\\testExcel.xlsx");
    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllbytes(path));
    return new ResposeEntity<byte[]>(resource.getByteArray(),responseHeaders,HttpStatus.OK);
}

This is called in a button click. After I click the button nothing happens. While debugging this java, I could see the bytestream. In developer tools of Mozilla, I could see successful HTTP response(response in bytestream of that excel file). As per resources available on internet, browser should automatically download the file, but that's not happening.

这是在按钮单击中调用的。点击按钮后没有任何反应。在调试这个java时,我可以看到字节流。在Mozilla的开发人员工具中,我可以看到成功的HTTP响应(该excel文件的字节流中的响应)。根据互联网上可用的资源,浏览器应自动下载文件,但这不会发生。

Why downloading is not happening in browser? What's more I need to do to make it work?

为什么在浏览器中没有发生下载?我还需要做些什么才能让它发挥作用?

NOTE : This is just for POC purpose. In actual time, I have to generate the excel file from database details, through Apache POI or some other APIs.

注意:这仅用于POC目的。实际上,我必须通过Apache POI或其他API从数据库详细信息生成excel文件。

1 个解决方案

#1


1  

The below works for me:

以下对我有用:

@RequestMapping("/")
public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {

    FileInputStream inputStream = new FileInputStream(new File("C:\\work\\boot\\pom.xml"));

    response.setHeader("Content-Disposition", "attachment; filename=\"testExcel.xlsx\"");
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

    ServletOutputStream outputStream = response.getOutputStream();
    IOUtils.copy(inputStream, outputStream);

    outputStream.close();
    inputStream.close();
}

#1


1  

The below works for me:

以下对我有用:

@RequestMapping("/")
public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {

    FileInputStream inputStream = new FileInputStream(new File("C:\\work\\boot\\pom.xml"));

    response.setHeader("Content-Disposition", "attachment; filename=\"testExcel.xlsx\"");
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

    ServletOutputStream outputStream = response.getOutputStream();
    IOUtils.copy(inputStream, outputStream);

    outputStream.close();
    inputStream.close();
}