namyesol / spring-mvc-tuesday

Apache License 2.0
0 stars 0 forks source link

파일 업로드 #11

Open namyesol opened 1 year ago

namyesol commented 1 year ago

Spring File Download 정리

Content-Disposition

Spring

AJAX

namyesol commented 11 months ago

Spring 4

@RequestMapping(value = "/{resourceIdentifier}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
// @ResponseBody // Needed for @Controller but not for @RestController.
public ResponseEntity<InputStreamResource> 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) // For Spring 5: APPLICATION_OCTET_STREAM
            .body(resource);
}
namyesol commented 11 months ago

For big size files, an user should, when downloading, wait for a period of time. You need to provide some following information to the browser:

Content-Disposition Content-Disposition: means information on the Header part of Response. It shows the contents expected to be displayed on the browser. inline: Content that will display automatically. attachment: Attached file form-data: Form data. ....

Content-Disposition: inline
Content-Disposition: attachment
Content-Disposition: attachment; filename="java-tutorial.pdf"

Content-Length contentLength: This is the size of content (Unit: byte). This information helps the browser to inform to users of the size of content prepared to be downloaded. Therefore, while downloading the browser, it is possible to notify to users of the number of bytes downloaded, display percentage downloaded, estimate remaining time.

Content-Type This information helps the browser to know which applications can open this content and suggest users to open by a program available on their computer when the content is downloaded successfully. Set Content-Type=application/octet-stream if you want the browser to download such content immediately without asking users.

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
namyesol commented 11 months ago

개념 정리 -- MVC / JSP / Spring(Boot) / JDBC / MyBatis / JPA / REST api