这是我们压缩包里面得内容。
直接上代码解释把
@ApiOperation("批量导入")
@GetMapping("/uploadZipSpareParts/{fileId}")
public Result uploadZipSpareParts(@PathVariable("fileId") String fileId) throws IOException {
ObsFileInfoDTO obsFileInfoDTO = new ObsFileInfoDTO();
obsFileInfoDTO.setGuids(Lists.newArrayList(fileId));
Result<List<ObsFileInfoVO>> fileResult = adminFeignClient.getFileTempUrl(obsFileInfoDTO);
ObsFileInfoVO obsFileInfoVO = fileResult.getData().get(0);
String fileUrl = obsFileInfoVO.getTempUrl();
InputStream downloadInputStreamByUrl = UnzipUtil.getDownloadInputStreamByUrl(fileUrl);
// 确保目标目录存在
String destDir = System.getProperty("user.dir");
// 解压后得文件夹地址
String path = UnzipUtil.saveFile(downloadInputStreamByUrl, obsFileInfoVO.getFileName(), destDir);
List<SparePartsExcelDTO> list;
try {
File copyFile = new File(path + "/备件库导入模板列表.xlsx");
InputStream inputStream = new FileInputStream(copyFile);
list = new ExcelUtil<>(SparePartsExcelDTO.class).importExcel(inputStream);
if (CollUtil.isEmpty(list) || list.size() <= 0) {
throw new CustomException("导入数据不能为空!");
}
LoginUser loginUser = SecurityUtils.getLoginUser();
for (SparePartsExcelDTO sparePartsExcelDTO : list) {
FactorySpareParts factorySpareParts = new FactorySpareParts();
BeanUtil.copyProperties(sparePartsExcelDTO, factorySpareParts);
factorySpareParts.setFactoryId(loginUser.getUser().getFactory());
factorySpareParts.setFactoryName(loginUser.getUser().getFactoryName());
// factorySpareParts.setFactoryId("SZHL");
// factorySpareParts.setFactoryName("深圳海雷");
factorySpareParts.setCreateTime(LocalDateTime.now());
factorySpareParts.setUpdateTime(LocalDateTime.now());
String picPath = path + "/" + sparePartsExcelDTO.getFacSparePic();
File fileInputStream = new File(picPath);
FileInputStream fileInput = new FileInputStream(fileInputStream);
byte[] byt = new byte[fileInput.available()];
fileInput.read(byt);
MultipartFile toMultipartFile = new MockMultipartFile("file", sparePartsExcelDTO.getFacSparePic(),"image/jpeg", byt);
AjaxResult uploadResult = adminFeignClient.upload(toMultipartFile, true, null);
if (uploadResult.get("data") != null) {
JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(uploadResult.get("data")));
String uploadFileId = jsonObject.getString("fileId");
ObsFileInfoDTO uploadObsFileInfoDTO = new ObsFileInfoDTO();
uploadObsFileInfoDTO.setGuids(Lists.newArrayList(uploadFileId));
Result<List<ObsFileInfoVO>> uploadFileResult = adminFeignClient.getFileTempUrl(uploadObsFileInfoDTO);
ObsFileInfoVO uploadObsFileInfoVO = uploadFileResult.getData().get(0);
factorySpareParts.setFacSparePic(uploadObsFileInfoVO.getTempUrl());
}
factorySparePartsService.save(factorySpareParts);
fileInput.close();
}
} catch (Exception e) {
log.info(e.getMessage(),e);
throw new CustomException("导入数据处理出错!");
}
// 最后将解压的文件夹删除
UnzipUtil.deleteFiles(path);
return Result.success("导入成功");
}
这里面请求地址得fileId 是前端上传的后fileId 这是我们框架自己的东西 所以大家不用理会
ObsFileInfoDTO obsFileInfoDTO = new ObsFileInfoDTO();
obsFileInfoDTO.setGuids(Lists.newArrayList(fileId));
Result<List<ObsFileInfoVO>> fileResult = adminFeignClient.getFileTempUrl(obsFileInfoDTO);
ObsFileInfoVO obsFileInfoVO = fileResult.getData().get(0);
String fileUrl = obsFileInfoVO.getTempUrl();
这里面主要是获取压缩包
InputStream downloadInputStreamByUrl = UnzipUtil.getDownloadInputStreamByUrl(fileUrl);
// 确保目标目录存在
String destDir = System.getProperty("user.dir");
// 解压后得文件夹地址
String path = UnzipUtil.saveFile(downloadInputStreamByUrl, obsFileInfoVO.getFileName(), destDir);
public static InputStream getDownloadInputStreamByUrl(String downloadUrl) {
if (ObjectUtils.isEmpty(downloadUrl)) {
throw new RuntimeException("无效参数:fileUrl 不能为空");
}
InputStream in = null;
try {
URL url = new URL(downloadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置超时时间为3秒
conn.setConnectTimeout(12 * 1000);
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// 得到输入流
in = conn.getInputStream();
} catch (Exception e) {
throw new RuntimeException(e);
}
return in;
}
这里面是将压缩包解压到指定位置,下面是saveFile方法的内容
public static String saveFile(InputStream downloadInputStreamByUrl,String fileName, String uploadDir) throws IOException {
String originalFilename = fileName;
// String mkdirsReal = originalFilename.split("\\.")[0];
File dir = new File(uploadDir);
if (!dir.exists()) {
dir.mkdirs();
}
try (ZipInputStream zipInputStream = new ZipInputStream(downloadInputStreamByUrl, Charset.forName("GBK"))) {
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
File outputFile = new File(uploadDir, entry.getName());
// 如果是目录,则创建目录
if (entry.isDirectory()) {
outputFile.mkdirs();
} else {
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
// 如果是文件,则解压文件
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outputFile))) {
byte[] buffer = new byte[1024];
int len;
while ((len = zipInputStream.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
}
}
zipInputStream.closeEntry();
}
} catch (Exception e) {
log.error(e.getMessage(), "读取zip保存指定目录失败......");
}
String realPath = uploadDir + "/" + originalFilename.split("\\.")[0];
log.info("解压的路径是:{}", realPath);
return realPath;
}
注意下saveFile方法中
之所以有这段代码是因为咱们正常使用的解压压缩工具(winrar)和window自带的压缩工具压缩出来的压缩包 ,对于ZipEntry是不一样 比如说目前我们压缩包里面的内容:/压缩包/aa/文件 是这样的结构 如果用winrar 那么ZipEntry读取出来就是先读/aa文件夹 再读下面文件 而对于windows自带的压缩出来压缩包 ZipEntry是直接读/aa/文件 等于少了一层 所以咱们要自己去创建上层文件夹 这样的话 就能符合我目前的构建方法了 具体的还是要你个人怎么读取压缩包的。
中间的代码是相对于好理解点的 我也懒得整理 代码像做饭的一样 然后在最后会把解压的文件删除掉 不要占用资源
// 最后将解压的文件夹删除
UnzipUtil.deleteFiles(path);
public static void deleteFiles (String source) {
File file = new File(source);
deleteDirectoryLegacyIO(file);
}
private static void deleteDirectoryLegacyIO(File file) {
if(file.isDirectory()) {
File[] files = file.listFiles();
if(files != null) { // 如果文件夹为空,files可能为null
for(File file1 : files) {
deleteDirectoryLegacyIO(file1); // 递归删除子文件夹和文件
}
}
}
file.delete(); // 删除空文件夹或者文件
}