Is it safe to return an ResponseEntity<InputStreamResource> that wraps S3Object.getObjectContent() in REST controller?

一曲冷凌霜 提交于 2020-01-23 17:59:08

问题


I'm developing an Spring Boot Application, that should allow users to download files indirectly from Amazon S3 via specified application REST interface. For this purpose I have an REST-Controller, that returns an InputStreamResource to the user like following:

@GetMapping(path = "/download/{fileId}")
public ResponseEntity<InputStreamResource> downloadFileById(@PathVariable("fileId") Integer fileId) {
    Optional<LocalizedFile> fileForDownload = fileService.getConcreteFileForDownload(fileId);

    if (!fileForDownload.isPresent()) {
        return ResponseEntity.notFound().build();
    }

    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileForDownload.get().getFilename())
            .body(new InputStreamResource(fileService.download(fileForDownload.get())));
}

Download method in file service looks like this:

@Override
public InputStream download(LocalizedFile file) {
    S3Object obj = s3client.getObject(bucketName, file.getFilename());
    return obj.getObjectContent();
}

My concern here is that this input stream from Amazon SDK could not be closed explicitly in controller. There is a following warning in AWS documentation of the getObjectContent() method, that makes me suspicious about success of my approach described above:

If you retrieve an S3Object, you should close this input stream as soon as possible, because the object contents aren't buffered in memory and stream directly from Amazon S3. Further, failure to close this stream can cause the request pool to become blocked.

Therefore my question: Is it safe to return an ResponseEntity<InputStreamResource> in controller? Will this InputStream from S3Object.getObjectContent() be closed automatically after successful download? So far my approach has worked successfully, but I'm not so sure about possible future consequences.


回答1:


After some research I've found an answer, that should be applicable to my question.

Tl;dr version: Spring MVC handles closing of the given input stream, that's why my approach described above should be safe.



来源:https://stackoverflow.com/questions/59582243/is-it-safe-to-return-an-responseentityinputstreamresource-that-wraps-s3object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!