Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set 'Content-Disposition' and 'Filename' when using FileSystemResource to force a file download file?

What is the most appropriate, and standard, way to set the Content-Disposition=attachment and filename=xyz.zip using Spring 3 FileSystemResource?

The action looks like :

@ResponseBody @RequestMapping(value = "/action/{abcd}/{efgh}", method = RequestMethod.GET, produces = "application/zip") @PreAuthorize("@authorizationService.authorizeMethod()") public FileSystemResource doAction(@PathVariable String abcd, @PathVariable String efgh) {      File zipFile = service.getFile(abcd, efgh);      return new FileSystemResource(zipFile); } 

Although the file is a zip file so the browser always downloads the file, but I would like to explicitly mention the file as attachment, and also provide a filename that has nothing to do with the files actual name.

There might be workarounds for this problem, but I would like to know the proper Spring and FileSystemResource way to achieve this goal.

P.S. The file that is being used here is a temporary file, marked for deletion when the JVM exists.

like image 234
Hassan Jamil Avatar asked May 17 '13 04:05

Hassan Jamil


People also ask

What is content-disposition attachment filename?

Content-Disposition is an optional header and allows the sender to indicate a default archival disposition; a filename. The optional "filename" parameter provides for this. This header field definition is based almost verbatim on Experimental RFC 1806 by R. Troost and S.

How do you use content-disposition?

In a regular HTTP response, the Content-Disposition response header is a header indicating if the content is expected to be displayed inline in the browser, that is, as a Web page or as part of a Web page, or as an attachment, that is downloaded and saved locally.

What is content-disposition in Java?

The MIME Content-disposition header provides presentation information for the body-part. It is often added to attachments specifying whether the attachment body part should be displayed (inline) or presented as a file name to be copied (attachment).


1 Answers

In addition to the accepted answer, Spring has the class ContentDisposition specific for this purpose. I believe it deals with the file name sanitization.

      ContentDisposition contentDisposition = ContentDisposition.builder("inline")           .filename("Filename")           .build();        HttpHeaders headers = new HttpHeaders();       headers.setContentDisposition(contentDisposition); 
like image 106
Jefferson Lima Avatar answered Sep 21 '22 17:09

Jefferson Lima