Home >Java >javaTutorial >How to Download Files Generated Dynamically Using Spring Controllers?

How to Download Files Generated Dynamically Using Spring Controllers?

Susan Sarandon
Susan SarandonOriginal
2024-12-23 13:16:23975browse

How to Download Files Generated Dynamically Using Spring Controllers?

Downloading Files from Spring Controllers

Many applications require the download of files from a website. In some cases, these files are generated dynamically using a framework such as Freemarker and a PDF generation library like iText. However, this raises the issue of how to allow users to download the file through a Spring Controller.

The solution involves using the HttpServletResponse object to write the file to the output stream. This can be achieved with the following code:

@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");
    }

}

Once the output stream is accessible, it can be used as the destination for the PDF generated by the PDF generator. Additionally, by setting the Content-Type to "application/pdf," the correct file type can be specified for the browser.

The above is the detailed content of How to Download Files Generated Dynamically 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