Spring - 响应文件流的正确方法是什么?

时间:2016-05-20 06:08:20

标签: java spring spring-mvc

我有一个控制器,它使用ResponseEntity类返回文件流。 但是我不确定在完成方法后资源是否已关闭。

@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(filePath)实现了Closeable,所以它应该在使用后关闭,但我找不到关闭它的代码。 :

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

要响应文件流,使用此代码提供文件是否合适?或者有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

使用Spring 4.1,您的方法将起作用,其中没有任何问题。 如果你想看,下面是另一种方法:

I0520 21:39:35.705278 30447 net.cpp:84] Creating Layer conv1
I0520 21:39:35.705286 30447 net.cpp:381] conv1 <- data
I0520 21:39:35.705294 30447 net.cpp:339] conv1 -> conv1
I0520 21:39:35.705307 30447 net.cpp:113] Setting up conv1
F0520 21:39:35.705329 30447 base_conv_layer.cpp:14] Check failed: 4 == bottom[0]->num_axes() (4 vs. 5) Input must have 4 axes, corresponding to (num, channels, height, width)