我对此进行了更多调试,并HttpServletRequest
在我的控制器方法中添加了一个,以查看那里是否有任何可用的东西。我发现我收到的请求是 a org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest
,其中有一个名为multipartParameters
which is just a的字段HashMap
。我发现这张地图的键是name
、chunks
和chunk
。所以,我决定尝试以下作为我的签名:
uploadMedia(@RequestBody MultipartFile file, @RequestParam String name, @RequestParam int chunks, @RequestParam int chunk)
果然,这些@RequestParam
参数分别填充了文件名、块数和块号(从零开始)。为每个请求提供此信息将使将块组装到最终文件中变得非常容易。
还要知道的一件事是,如果文件不需要分块(文件大小小于块大小),则不会发送chunks
and参数。chunk
所以,我的最终签名最终看起来像这样:
uploadMedia(@RequestBody MultipartFile file, @RequestParam String name, @RequestParam(required=false, defaultValue="-1") int chunks, @RequestParam(required=false, defaultValue="-1") int chunk)
然后我可以检查 -1 看看我是否需要担心分块。
所以,在控制器方法本身我有这样的事情:
Media media = new Media();
//set stuff on my Media object for storing info about the file in the DB
//....
if (chunks > 0 && chunk > 0)
{
//Need to append the bytes in this chunk
mediaRepository.appendBytes(media, file.getBytes());
if (chunk == chunks - 1)
{
//last chunk, upload is done
onUploadFinished(media);
}
}
else
{
//Write out the first set of bytes
mediaRepository.saveBytes(media, file.getBytes());
if (chunks <= 0)
{
//no chunks were needed, all the bytes have been written out, upload is done
onUploadFinished(media);
}
}