457

I have a requirement where I need to download a PDF from the website. The PDF needs to be generated within the code, which I thought would be a combination of a freemarker and a PDF generation framework like iText. Is there any better way?

However, my main problem is how do I allow the users to download the file through a Spring Controller?

2
  • 4
    It worth mentioning that Spring Framework changed a lot since 2011, so you can do it in a reactive way as well - here is an example Aug 9, 2019 at 7:32
  • 1
    With later versions of spring, you just need to return the byte array with appropriate headers in ResponseEntity. Here is a full example: allaboutspringframework.com/… Mar 29, 2021 at 13:36

16 Answers 16

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

}

Generally speaking, when you have response.getOutputStream(), you can write anything there. You can pass this output stream as a place to put generated PDF to your generator. Also, if you know what file type you are sending, you can set

response.setContentType("application/pdf");
13
  • 4
    This is pretty much what I was about to say, but you should probably also set the response type header to something appropriate for the file.
    – GaryF
    Apr 15, 2011 at 7:01
  • 2
    Yep, just edited the post. I had various file types generated, so I left it to the browser to determine the content type of the file by its extension.
    – Infeligo
    Apr 15, 2011 at 7:05
  • 42
    Any particular reason to use Apache's IOUtils instead of Spring's FileCopyUtils?
    – Powerlord
    Sep 18, 2012 at 16:12
  • 4
    Here is a better solution: stackoverflow.com/questions/16652760/… Jul 14, 2015 at 15:16
  • 2
    @Powerlord Spring method closes the streams, Apache one does not. There are debates if the Servlet response output stream should be closed in the Controller code or by the Servlet container ...
    – Comencau
    Mar 7, 2018 at 21:04
307

I was able to stream line this by using the built in support in Spring with it's ResourceHttpMessageConverter. This will set the content-length and content-type if it can determine the mime-type

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
@ResponseBody
public FileSystemResource getFile(@PathVariable("file_name") String fileName) {
    return new FileSystemResource(myService.getFileFor(fileName)); 
}
14
  • 14
    This works. But the file (.csv file) is displayed in the browser and not downloaded - how can I force the browser to download?
    – chzbrgla
    Jul 12, 2013 at 8:26
  • 49
    You can add produces = MediaType.APPLICATION_OCTET_STREAM_VALUE to the @RequestMapping to force download
    – David Kago
    Sep 25, 2013 at 17:33
  • 8
    Also You should add <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/> to messageConverters list (<mvc:annotation-driven><mvc:message-converters>)
    – Enginer
    Nov 29, 2013 at 12:15
  • 5
    Is there a way to set the Content-Disposition header with this way?
    – Ralph
    Apr 15, 2015 at 12:54
  • 10
    I didn't have a need for that, but I think you could add HttpResponse as a parameter to the method, and then "response.setHeader("Content-Disposition", "attachment; filename=somefile.pdf");" Apr 16, 2015 at 13:42
88

You should be able to write the file on the response directly. Something like

response.setContentType("application/pdf");      
response.setHeader("Content-Disposition", "attachment; filename=\"somefile.pdf\""); 

and then write the file as a binary stream on response.getOutputStream(). Remember to do response.flush() at the end and that should do it.

5
  • 8
    isn't the 'Spring' way to set the content type like this? @RequestMapping(value = "/foo/bar", produces = "application/pdf")
    – Black
    May 7, 2014 at 5:44
  • 4
    @Francis what if your application downloads different file types? Lobster1234's answer enables you to dynamically set the content disposition.
    – Rose
    Nov 13, 2015 at 2:29
  • 2
    that's true @Rose, but I believe it would be better practice to define different end-points per format
    – Black
    Nov 13, 2015 at 3:10
  • 3
    I guess not, because it's not scalable. We are currently supporting a dozen types of resources. We might support more file types based on what users want to upload in that case we might end up with so many end points essentially doing the same thing. IMHO there has to be only one download end point and it handles multitude of file types. @Francis
    – Rose
    Nov 13, 2015 at 5:12
  • 3
    it's absolutely "scalable", but we can agree to disagree whether it's the best practice
    – Black
    Nov 16, 2015 at 22:42
83

With Spring 3.0 you can use the HttpEntity return object. If you use this, then your controller does not need a HttpServletResponse object, and therefore it is easier to test. Except this, this answer is relative equals to the one of Infeligo.

If the return value of your pdf framework is an byte array (read the second part of my answer for other return values) :

@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
                 @PathVariable("fileName") String fileName) throws IOException {

    byte[] documentBody = this.pdfFramework.createPdf(filename);

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
                   "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(documentBody.length);

    return new HttpEntity<byte[]>(documentBody, header);
}

If the return type of your PDF Framework (documentBbody) is not already a byte array (and also no ByteArrayInputStream) then it would been wise NOT to make it a byte array first. Instead it is better to use:

example with FileSystemResource:

@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
                 @PathVariable("fileName") String fileName) throws IOException {

    File document = this.pdfFramework.createPdf(filename);

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
                   "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(document.length());

    return new HttpEntity<byte[]>(new FileSystemResource(document),
                                  header);
}
6
  • 15
    -1 this will un-neccessarily load the whole file in memory can easily casue OutOfMemoryErrors. Mar 7, 2014 at 12:39
  • 2
    @FaisalFeroz: yes this is right, but the file document is anyway created in memory (see the question: "PDF needs to be generated within the code"). Anyway - what is your solution that overcome this problem?
    – Ralph
    Mar 7, 2014 at 17:30
  • 1
    You may also use ResponseEntity which is a super of HttpEntity which allows you to specify the response http status code. Example: return new ResponseEntity<byte[]>(documentBody, headers, HttpStatus.CREATED) Oct 8, 2014 at 11:16
  • @Amr Mostafa: ResponseEntity is a subclass of HttpEntity (but I get it) on the other hand 201 CREATED is not what I would use when I return just an view to the data. (see w3.org/Protocols/rfc2616/rfc2616-sec10.html for 201 CREATED)
    – Ralph
    Oct 8, 2014 at 12:39
  • 1
    Is there a reason why you are replacing whitespaces with underscore in the filename? You can wrap it in quotes to send the actual name. Oct 22, 2018 at 13:15
81

If you:

  • Don't want to load the whole file into a byte[] before sending to the response;
  • Want/need to send/download it via InputStream;
  • Want to have full control of the Mime Type and file name sent;
  • Have other @ControllerAdvice picking up exceptions for you (or not).

The code below is what you need:

@RequestMapping(value = "/stuff/{stuffId}", method = RequestMethod.GET)
public ResponseEntity<FileSystemResource> downloadStuff(@PathVariable int stuffId)
                                                                      throws IOException {
    String fullPath = stuffService.figureOutFileNameFor(stuffId);
    File file = new File(fullPath);
    long fileLength = file.length(); // this is ok, but see note below

    HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentType("application/pdf");
    respHeaders.setContentLength(fileLength);
    respHeaders.setContentDispositionFormData("attachment", "fileNameIwant.pdf");

    return new ResponseEntity<FileSystemResource>(
        new FileSystemResource(file), respHeaders, HttpStatus.OK
    );
}

More on setContentLength(): First of all, the content-length header is optional per the HTTP 1.1 RFC. Still, if you can provide a value, it is better. To obtain such value, know that File#length() should be good enough in the general case, so it is a safe default choice.
In very specific scenarios, though, it can be slow, in which case you should have it stored previously (e.g. in the DB), not calculated on the fly. Slow scenarios include: if the file is very large, specially if it is on a remote system or something more elaborated like that - a database, maybe.



InputStreamResource

If your resource is not a file, e.g. you pick the data up from the DB, you should use InputStreamResource. Example:

InputStreamResource isr = new InputStreamResource(...);
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
10
  • You don't advise for the use of the FileSystemResource class ?
    – Stephane
    Nov 4, 2014 at 22:39
  • Actually, I do believe it is OK to use the FileSystemResource there. It is even advisable if your resource is a file. In this sample, FileSystemResource can be used where InputStreamResource is.
    – acdcjunior
    Apr 27, 2015 at 15:35
  • About the file length calculation part: If you are worried, don't be. File#length() should be good enough in the general case. I just mentioned it because it does can be slow, specially if the file is in a remote system or something more elaborated like that - a database, maybe?. But only worry if it becomes a problem (or if you have hard evidence it will become one), not before. The main point is: you are making an effort to stream the file, if you have to preload all of it before, then the streaming ends up making no difference, eh?
    – acdcjunior
    May 13, 2015 at 15:21
  • why does the above code not working for me ? It downloads 0 bytes file. I checked and made sure ByteArray & ResourceMessage converters are there. Am I missing something ? Nov 2, 2015 at 17:01
  • Why are you worrying about ByteArray & ResourceMessage converters?
    – acdcjunior
    Nov 2, 2015 at 22:44
65
+100

Do

  1. Return ResponseEntity<Resource> from a handler method
  2. Specify Content-Type
  3. Set Content-Disposition if necessary:
    1. filename
    2. type
      1. inline to force preview in a browser
      2. attachment to force a download

Example

@Controller
public class DownloadController {
    @GetMapping("/downloadPdf.pdf")
    // 1.
    public ResponseEntity<Resource> downloadPdf() {
        FileSystemResource resource = new FileSystemResource("/home/caco3/Downloads/JMC_Tutorial.pdf");
        // 2.
        MediaType mediaType = MediaTypeFactory
                .getMediaType(resource)
                .orElse(MediaType.APPLICATION_OCTET_STREAM);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);
        // 3
        ContentDisposition disposition = ContentDisposition
                // 3.2
                .inline() // or .attachment()
                // 3.1
                .filename(resource.getFilename())
                .build();
        headers.setContentDisposition(disposition);
        return new ResponseEntity<>(resource, headers, HttpStatus.OK);
    }
}

Explanation

Return ResponseEntity<Resource>

When you return a ResponseEntity<Resource>, the ResourceHttpMessageConverter writes file contents

Examples of Resource implementations:

Specify Content-Type explicitly:

Reason: see "FileSystemResource is returned with content type json" question

Options:

  • Hardcode the header
  • Use the MediaTypeFactory from Spring. The MediaTypeFactory maps Resource to MediaType using the /org/springframework/http/mime.types file
  • Use a third party library like Apache Tika

Set Content-Disposition if necessary:

About Content-Disposition header:

The first parameter in the HTTP context is either inline (default value, indicating it can be displayed inside the Web page, or as the Web page) or attachment (indicating it should be downloaded; most browsers presenting a 'Save as' dialog, prefilled with the value of the filename parameters if present).

Use ContentDisposition in application:

  • To preview a file in a browser:

    ContentDisposition disposition = ContentDisposition
            .inline()
            .filename(resource.getFilename())
            .build();
    
  • To force a download:

    ContentDisposition disposition = ContentDisposition
            .attachment()
            .filename(resource.getFilename())
            .build();
    

Use InputStreamResource carefully:

Specify Content-Length using the HttpHeaders#setContentLength method if:

  1. The length is known
  2. You use InputStreamResource

Reason: Spring won't write Content-Length for InputStreamResource because Spring can't determine the length of the resource. Here is a snippet of code from ResourceHttpMessageConverter:

@Override
protected Long getContentLength(Resource resource, @Nullable MediaType contentType) throws IOException {
    // Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
    // Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
    if (InputStreamResource.class == resource.getClass()) {
        return null;
    }
    long contentLength = resource.contentLength();
    return (contentLength < 0 ? null : contentLength);
}

In other cases Spring sets the Content-Length:

~ $ curl -I localhost:8080/downloadPdf.pdf  | grep "Content-Length"
Content-Length: 7554270
3
  • 10
    This should be the accepted answer. It seems to provide the only clean handling of ContentDisposition and gives clear explanations. Sep 25, 2020 at 9:24
  • 5
    Definitely the best answer Dec 30, 2020 at 23:57
  • 2
    Works perfectly, and works with "springdoc-openapi-ui" v1.5.11, swagger-ui. The "Download" link appears as expected with "attachment()" flag. Oct 7, 2021 at 12:49
24

This code is working fine to download a file automatically from spring controller on clicking a link on jsp.

@RequestMapping(value="/downloadLogFile")
public void getLogFile(HttpSession session,HttpServletResponse response) throws Exception {
    try {
        String filePathToBeServed = //complete file name with path;
        File fileToDownload = new File(filePathToBeServed);
        InputStream inputStream = new FileInputStream(fileToDownload);
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment; filename="+fileName+".txt"); 
        IOUtils.copy(inputStream, response.getOutputStream());
        response.flushBuffer();
        inputStream.close();
    } catch (Exception e){
        LOGGER.debug("Request could not be completed at this moment. Please try again.");
        e.printStackTrace();
    }

}
1
20

Below code worked for me to generate and download a text file.

@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDownloadData() throws Exception {

    String regData = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
    byte[] output = regData.getBytes();

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("charset", "utf-8");
    responseHeaders.setContentType(MediaType.valueOf("text/html"));
    responseHeaders.setContentLength(output.length);
    responseHeaders.set("Content-disposition", "attachment; filename=filename.txt");

    return new ResponseEntity<byte[]>(output, responseHeaders, HttpStatus.OK);
}
6

What I can quickly think of is, generate the pdf and store it in webapp/downloads/< RANDOM-FILENAME>.pdf from the code and send a forward to this file using HttpServletRequest

request.getRequestDispatcher("/downloads/<RANDOM-FILENAME>.pdf").forward(request, response);

or if you can configure your view resolver something like,

  <bean id="pdfViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
              value="org.springframework.web.servlet.view.JstlView" />
    <property name="order" value=”2″/>
    <property name="prefix" value="/downloads/" />
    <property name="suffix" value=".pdf" />
  </bean>

then just return

return "RANDOM-FILENAME";
1
  • 1
    If I need two view resolvers, how can I also return the name of resolver or choose it in controller??
    – azerafati
    Jun 12, 2014 at 17:00
4

The following solution work for me

    @RequestMapping(value="/download")
    public void getLogFile(HttpSession session,HttpServletResponse response) throws Exception {
        try {

            String fileName="archivo demo.pdf";
            String filePathToBeServed = "C:\\software\\Tomcat 7.0\\tmpFiles\\";
            File fileToDownload = new File(filePathToBeServed+fileName);

            InputStream inputStream = new FileInputStream(fileToDownload);
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename="+fileName); 
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
            inputStream.close();
        } catch (Exception exception){
            System.out.println(exception.getMessage());
        }

    }
3

something like below

@RequestMapping(value = "/download", method = RequestMethod.GET)
public void getFile(HttpServletResponse response) {
    try {
        DefaultResourceLoader loader = new DefaultResourceLoader();
        InputStream is = loader.getResource("classpath:META-INF/resources/Accepted.pdf").getInputStream();
        IOUtils.copy(is, response.getOutputStream());
        response.setHeader("Content-Disposition", "attachment; filename=Accepted.pdf");
        response.flushBuffer();
    } catch (IOException ex) {
        throw new RuntimeException("IOError writing file to output stream");
    }
}

You can display PDF or download it examples here

2

If it helps anyone. You can do what the accepted answer by Infeligo has suggested but just put this extra bit in the code for a forced download.

response.setContentType("application/force-download");
1

In my case I'm generating some file on demand, so also url has to be generated.

For me works something like that:

@RequestMapping(value = "/files/{filename:.+}", method = RequestMethod.GET, produces = "text/csv")
@ResponseBody
public FileSystemResource getFile(@PathVariable String filename) {
    String path = dataProvider.getFullPath(filename);
    return new FileSystemResource(new File(path));
}

Very important is mime type in produces and also that, that name of the file is a part of the link so you has to use @PathVariable.

HTML code looks like that:

<a th:href="@{|/dbreport/files/${file_name}|}">Download</a>

Where ${file_name} is generated by Thymeleaf in controller and is i.e.: result_20200225.csv, so that whole url behing link is: example.com/aplication/dbreport/files/result_20200225.csv.

After clicking on link browser asks me what to do with file - save or open.

1

I had to add this to download any file

    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition",
            "attachment;filename="+"file.txt");

all code:

@Controller
public class FileController {

@RequestMapping(value = "/file", method =RequestMethod.GET)
@ResponseBody
public FileSystemResource getFile(HttpServletResponse response) {

    final File file = new File("file.txt");
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition",
            "attachment;filename="+"file.txt");
    return new FileSystemResource(file);
 }
}
0

This can be a useful answer.

Is it ok to export data as pdf format in frontend?

Extending to this, adding content-disposition as an attachment(default) will download the file. If you want to view it, you need to set it to inline.

0

Very simple way to do it with SpringBoot:

import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;    

@GetMapping("/file/{fileName}")
public ResponseEntity<byte[]> getFile(@PathVariable String fileName) {
        // Create Headers for "forcing download"
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        // Headers for giving a custom name to the file and also the file extension, in this example .zip
        httpHeaders.set(HttpHeaders.CONTENT_DISPOSITION,
            ContentDisposition.attachment().filename(String.format("%s.%s", fileName, "zip")).build().toString());
        // Get the bytes from your service (for example an aws bucket)
        return ResponseEntity.ok().headers(httpHeaders).body(service.getFile(fileName));
    }

the above code works, but its only for showing you how simple and easy it can be, but you should first check if the file exists before doing anything, then create the headers in another method and finally return (for clean code).

Not the answer you're looking for? Browse other questions tagged or ask your own question.