Reputation: 45
I have a controller which returns file stream using ResponseEntity class. But I'm not sure if the resource is closed after finished the method.
@RequestMapping(value = "/VMS-49001/playlist/{listName:.+}")
@ResponseBody
public ResponseEntity<?> playlist(HttpServletRequest request, HttpServletResponse response,
@PathVariable String listName) throws IOException {
String hlsPath = getHLSPath(request.getParameter("dt"), listName, OtuEnum.URLType.HLS);
Path filePath = Paths.get(hlsPath);
if (filePath.toFile().exists()) {
Path fileNamePath = filePath.getFileName();
String fileName = "";
if (fileNamePath != null) {
fileName = fileNamePath.toString();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData(fileName, fileName);
return ResponseEntity.ok().contentLength(filePath.toFile().length())
.contentType(MediaType.parseMediaType("application/vnd.apple.mpegurl")).headers(headers)
.body(new InputStreamResource(Files.newInputStream(filePath)));
} else {
String errorMsg = "404 file not found";
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.contentType(MediaType.parseMediaType("text/html"))
.body(errorMsg);
}
}
if you see below code fragment, Files.newInputStream(filePath) implements Closeable, so it should be closed after use but I can't find the code closing it. :
return ResponseEntity.ok()
.contentLength(filePath.toFile().length())
.contentType(MediaType.parseMediaType("application/vnd.apple.mpegurl"))
.headers(headers)
.body(new InputStreamResource(Files.newInputStream(filePath)));
To response file stream, is it good to serve the file with this code? Or is there any better approach?
Upvotes: 2
Views: 995
Reputation: 1567
With Spring 4.1 your approach will work there is no issue in it. Here below is another approach in case if you want to look :
@RequestMapping(value = "/VMS-49001/playlist/{listName:.+}")
public ResponseEntity<byte[]> testphoto() throws IOException {
InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/vnd.apple.mpegurl"));
headers.setContentDispositionFormData(fileName, fileName);
return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
}
Upvotes: 2