2016-05-20 71 views
2

我有一個控制器,它使用ResponseEntity類返回文件流。 但我不確定資源在完成該方法後是否關閉。Spring - 響應文件流的正確方法是什麼?

@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); 
    } 
} 

如果你看到下面的代碼片段,Files.newInputStream(文件路徑)實現了可關閉的,所以使用後應關閉,但我找不到代碼關閉它。 :

return ResponseEntity.ok() 
    .contentLength(filePath.toFile().length()) 
    .contentType(MediaType.parseMediaType("application/vnd.apple.mpegurl")) 
    .headers(headers) 
    .body(new InputStreamResource(Files.newInputStream(filePath))); 

爲了響應文件流,用這段代碼服務文件是否好?或者有沒有「正確」的方法?

回答

2

有了Spring 4.1,你的方法就可以工作,沒有問題了。 下面是另一種情況下的方法,如果你想看看:

@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); 
} 
相關問題