数据压缩下载
服务端生成数据(数据库查询结果)-> 生成文件,压缩成zip下载到本地
zip压缩文件上传
zip数据文件解析处理
文件zip压缩下载注意:
要为ZipEntry设置好size,不然会导致解析文件的时候出现zipEntry.getSize() 为 -1的问题。
下载部分:
@GetMapping("/exportUserData/{catalog}")
public void export(@PathVariable("catalog") String catalog,HttpServletResponse response) {
List<User> data = userService.queryUserByCatalog(catalog);
byte[] file = JSON.toJSONString(data).getBytes();
InputStream inputStream = new ByteArrayInputStream(file);
// 设置相关格式
response.setContentType("application/x-zip-compressed");
// 设置下载后的文件名以及header
response.addHeader("Content-disposition", "attachment;fileName=" + "user.zip");
// 创建输出对象
OutputStream os = response.getOutputStream();
ZipOutputStream out = new ZipOutputStream(os);
ZipEntry zipEntry = new ZipEntry("user.json");
zipEntry.setSize(file.length);
zipEntry.setMethod(ZipEntry.STORED);
CRC32 crc = new CRC32();
crc.reset();
crc.update(file);
zipEntry.setCrc(crc.getValue());
out.putNextEntry(zipEntry);
IOUtils.copy(inputStream, out);
inputStream.close();
out.closeEntry();
out.close();
}
上传处理部分:
@PostMapping("/importUser/{catalog}")
public Result<?> importUser(@RequestParam("file") MultipartFile file, @PathVariable("catalog") String catalog)
throws IOException {
if (file.isEmpty()) {
return Result.ofFail(-1, "获取文件失败");
}
String filename = file.getOriginalFilename();
if (!filename.endsWith("zip")) {
return Result.ofFail(-1, "传入文件格式不是zip文件");
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(file.getBytes());
ZipInputStream zipInputStream = new ZipInputStream(byteArrayInputStream);
ZipEntry zipEntry = zipInputStream.getNextEntry();
byte[] bytes = new byte[(int) zipEntry.getSize()];
zipInputStream.read(bytes, 0, (int) zipEntry.getSize());
String userJson = new String(bytes, StandardCharsets.UTF_8);
userService.importUser(catalog, userJson);
return Result.ofSuccess("导入成功");
}