上传压缩包
- 访问地址:POST:/upload

/**
* 处理压缩包上传
*/
@PostMapping("/upload")
public Object uploadZipFile(@RequestParam("file") MultipartFile file) {
ModelAndView mv = new ModelAndView("zipUpload");
String path = "C:/upload/zipFiles/";
// 检查文件是否为空
if (file.isEmpty()) {
mv.addObject("message", "请选择要上传的压缩包");
return mv;
}
// 检查文件类型是否为压缩包
String originalFilename = file.getOriginalFilename();
if (!originalFilename.endsWith(".zip") && !originalFilename.endsWith(".rar")) {
mv.addObject("message", "请上传ZIP或RAR格式的压缩包");
return mv;
}
try {
// 创建存储目录(若不存在)
Path uploadPath = Paths.get(path);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
// 保存文件到服务器
String filePath = path + originalFilename;
file.transferTo(new File(filePath));
mv.addObject("message", "压缩包上传成功:" + originalFilename);
mv.addObject("fileName", originalFilename);
} catch (IOException e) {
e.printStackTrace();
mv.addObject("message", "上传失败:" + e.getMessage());
}
return JSON.toJSON(mv);
}
- 上传路径

下载压缩包
- 访问地址 GET:/download/1234567.zip
/**
* 下载压缩包
*/
@GetMapping("/download/{fileName:.+}")
public ResponseEntity<byte[]> downloadZipFile(@PathVariable String fileName) {
// 构建文件路径
File file = new File("C:/upload/zipFiles/" + fileName);
// 检查文件是否存在
if (!file.exists() || !file.isFile()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
try {
// 读取文件内容
byte[] fileContent = Files.readAllBytes(file.toPath());
// 处理文件名编码
String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name())
.replace("+", "%20");
// 设置响应头
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename*=UTF-8''" + encodedFileName);
// 根据文件类型设置Content-Type
if (fileName.endsWith(".zip")) {
headers.add(HttpHeaders.CONTENT_TYPE, "application/zip");
} else if (fileName.endsWith(".rar")) {
headers.add(HttpHeaders.CONTENT_TYPE, "application/x-rar-compressed");
}
headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(fileContent.length));
return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
- 下载效果

- Send and Download(response.zip)