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

后端 未结 5 632
囚心锁ツ
囚心锁ツ 2020-12-13 17:52

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

5条回答
  •  伪装坚强ぢ
    2020-12-13 18:36

    Here is an alternative approach for Spring 4. Note that this example clearly does not use good practices regarding filesystem access, this is just to demonstrate how some properties can be set declaratively.

    @RequestMapping(value = "/{resourceIdentifier}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    // @ResponseBody // Needed for @Controller but not for @RestController.
    public ResponseEntity download(@PathVariable(name = "resourceIdentifier") final String filename) throws Exception
    {
        final String resourceName = filename + ".dat";
        final File iFile = new File("/some/folder", resourceName);
        final long resourceLength = iFile.length();
        final long lastModified = iFile.lastModified();
        final InputStream resource = new FileInputStream(iFile);
    
        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=" + resourceName)
                .contentLength(resourceLength)
                .lastModified(lastModified)
                .contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE)
                .body(resource);
    }
    

提交回复
热议问题