问题
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