首页 > 解决方案 > 如何在不丢失元数据的情况下从 InputStream 保存视频文件?

问题描述

我有一个方法,它接受形式的文件InputStream并将其InputStream返回给用户。当用户从视频文件中保存InputStream视频文件时无法播放。接收和返回文件的方法如下所示:

@RequestMapping(value = "/file_redirect", method = RequestMethod.POST)
public ResponseEntity fileRedirect(HttpServletRequest request) throws Exception{

    InputStreamResource inputStreamResource = new InputStreamResource(request.getInputStream());

    return new ResponseEntity(inputStreamResource, HttpStatus.OK);
}

curl用来发送请求和接收文件:

curl -X POST -H "content-length: 389907412" -H "Content-Type: multipart/form-data" -F "data=@/path/to/file/myVideo.mp4" -o returnedVideo.mp4 localhost/file_redirect

我也试过这个方法(文件大小是正确的):

@RequestMapping(value = "/file_redirect", method = RequestMethod.POST)
public ResponseEntity fileRedirect(HttpServletRequest request) throws Exception{

    InputStreamResource inputStreamResource = new InputStreamResource(request.getInputStream());

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentLength(389907412);
    httpHeaders.setContentType(new MediaType("video", "mp4"));

    return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);    
}

两种方法都“有效”并且文件已成功保存,但之后无法播放。返回文件的文件大小是正确的。返回文件的元数据丢失。原始文件和返回文件的文件类型均为MPEG-4 video (video/mp4). 原始文件和返回文件的校验和不同。

保存文件时我做错了什么?为什么元数据会在返回的文件中丢失?

标签: javacurlvideofile-uploadinputstream

解决方案


问题出在curl请求本身而不是控制器中。似乎数据是作为一个字段发送的data,这就是为什么当我在控制器中获取 InputStream 时, InputStream 包含data带有值(文件)本身的字段。要发送没有字段的数据,我们需要使用下一个命令:

curl -X POST -H "content-length: 389907412" --data-binary "@/path/to/file/myVideo.mp4" -o returnedVideo.mp4 localhost/file_redirect

推荐阅读