java 接收分片上传文件代码
时间: 2023-11-25 08:05:50 浏览: 70
以下是Java实现接收分片上传文件的示例代码:
```java
@PostMapping("/upload")
public ResponseEntity<String> upload(@RequestParam("file") MultipartFile multipartFile,
@RequestParam(value = "chunk", required = false, defaultValue = "0") int chunk,
@RequestParam(value = "chunks", required = false, defaultValue = "1") int chunks,
HttpServletRequest request) throws IOException {
String fileName = multipartFile.getOriginalFilename();
// 获取上传目录
String uploadDir = request.getSession().getServletContext().getRealPath("/") + "/upload/";
// 如果目录不存在,则创建目录
File dir = new File(uploadDir);
if (!dir.exists()) {
dir.mkdirs();
}
// 如果是分片上传,将分片文件保存到临时目录
if (chunks > 1) {
File dest = new File(uploadDir + "temp/" + fileName + "_" + chunk);
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), dest);
return ResponseEntity.ok().body("Chunk " + chunk + " of " + chunks + " uploaded successfully");
}
// 如果是单文件上传,将所有分片合并成最终文件
File dest = new File(uploadDir + fileName);
if (dest.exists()) {
dest.delete();
}
for (int i = 0; i < chunks; i++) {
File partFile = new File(uploadDir + "temp/" + fileName + "_" + i);
FileOutputStream fos = new FileOutputStream(dest, true);
FileInputStream fis = new FileInputStream(partFile);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
partFile.delete();
}
return ResponseEntity.ok().body("File uploaded successfully");
}
```
在以上代码中,`chunk`和`chunks`参数分别表示当前分片的索引和总分片数。如果`chunks`大于1,表示当前是分片上传,将分片文件保存到临时目录。如果`chunks`等于1,表示当前是单文件上传,将所有分片合并成最终文件。最终文件保存的路径为上传目录下的原始文件名。如果上传目录不存在,则创建目录。注意,以上代码仅为示例,实际应用中需要根据具体情况进行修改和完善。
阅读全文