有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何用Spring/MultipartFile捕获中断流

我有一个Spring Boot应用程序,它是移动/web应用程序的API。其中一个端点接受多部分文件(图像或视频),如下所示:

@RequestMapping(value = "/x/y/z", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> post(@RequestParam("file") MultipartFile file) {
...
}

调用该方法时,我获取文件内容并将其保存在某个位置。然而,我注意到一个bug-如果我在上传过程中关闭移动应用上的网络连接,我在API端不会得到任何类型的IOException,我最终会得到一个截断的字节数组:

try {
 InputSteam inputStream = file.getInputStream();
 byte[] allBytes = IOUtils.toByteArray(inputStream);
 inputStream.close();
} catch (Exception ex) {
  //never get to this
}

所以问题是:如何确保流没有中断

使用Spring Boot:

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.3.3.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    在您可以在控制器内访问之前,Multipart流已经加载到服务器

    使用checksum确保文件不被中断

    计算并与Multipart数据一起发送:

    @RequestMapping(...)
    public ResponseEntity<?> post(@RequestParam("file") MultipartFile file,
                                  @RequestParam("checksum") String checksum) {
        ...
    }
    

    之后,您可以在服务器端重新计算checksum,以便检索实际的checksum,以便在请求验证范围内与接收到的checksum进行比较