Home >Java >javaTutorial >How to Stream Files for Download Using Spring Controllers?

How to Stream Files for Download Using Spring Controllers?

DDD
DDDOriginal
2024-12-23 01:34:45321browse

How to Stream Files for Download Using Spring Controllers?

Downloading Files from Spring Controllers

When facing the need to download a PDF from a website, it's common to consider generating the file dynamically using a combination of freemarker and PDF frameworks like iText. However, exploring additional options can lead to more efficient solutions.

One effective approach is to utilize Spring Controllers to handle file downloads. To achieve this, you can leverage the HttpServletResponse class provided by Spring. The following code sample illustrates how to set up a controller for file download:

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
public void getFile(
    @PathVariable("file_name") String fileName, 
    HttpServletResponse response) {
    try {
      // get your file as InputStream
      InputStream is = ...;
      // copy it to response's OutputStream
      org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
      response.flushBuffer();
    } catch (IOException ex) {
      log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
      throw new RuntimeException("IOError writing file to output stream");
    }
}

By utilizing response.getOutputStream(), you can stream any data, including generated PDFs, to the client. Additionally, you can specify the file type by setting response.setContentType(). For PDFs, this would be response.setContentType("application/pdf");.

The above is the detailed content of How to Stream Files for Download Using Spring Controllers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn