1,根据前端传过来的文件路径获取文件
2,把文件打成一个zip压缩包,把压缩包路径传给前端
3,前端下载完压缩包之后请求删除压缩包的方法
/**
* 存放简历压缩包临时文件的文件夹名
*/
public static final String RESUME_ZIP_MKDIR = "/resumeZip/";
/**
* 简历压缩
* @param ids
* @return
*/
@GetMapping("/zip/{ids}")
public AjaxResult zip(@PathVariable Long[] ids){
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();//D:/ruoyi/uploadPath/upload
/*获取简历列表*/
List<XykEmploymentResume> resumes = xykEmploymentResumeService.selectInfoByIds(ids);
//获取时间戳(用来生成压缩包名称,防止压缩包名称重复)
Long timeMillis = System.currentTimeMillis();
String path = filePath+RESUME_ZIP_MKDIR;
//简历压缩
compression(filePath, path, resumes,timeMillis);
//返回简历
return AjaxResult.success("profile/upload"+RESUME_ZIP_MKDIR+timeMillis+"jianli.zip");
}
/**
* 压缩简历
* @param path 文件路径
* @param zipFileName 压缩包名
* @param resumes 简历对象列表
*/
private static void compression(String path,String zipFileName,List<XykEmploymentResume> resumes,Long timeMillis){
ZipOutputStream zos = null;
try {
File zipMkdir = new File(zipFileName);
if (!zipMkdir.exists()){
boolean mkdir = zipMkdir.mkdirs();
}
File zipFile = new File(zipMkdir,timeMillis+"jianli.zip");
/*设置压缩文件*/
FileOutputStream fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(fos);
/*获取目标文件*/
int i = 1;
for (XykEmploymentResume resume : resumes) {
/*获取文件地址,判断文件路径是否正确*/
if (resume.getFilePath()==null||"".equals(resume.getFilePath())||!resume.getFilePath().startsWith("/profile/upload")){
continue;
}
String fileUrl = resume.getFilePath().substring(resume.getFilePath().lastIndexOf("upload/")+6);
File file = new File(path+fileUrl);
if (!file.exists()){
continue;
}
FileInputStream fis = new FileInputStream(file);
//把文件添加到压缩包中
String fileName = i+++resume.getUserName()+"-"+resume.getFileName();//自定义文件名
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
// 将文件内容写入压缩包
byte[] bytes = new byte[1024];
int len;
while ((len=fis.read(bytes))!=-1){
zos.write(bytes,0,len);
}
/*关闭输入流*/
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭输出
try {
assert zos != null;
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 删除压缩文件
* @param zipPath 压缩文件路径
*/
@PostMapping("/zip/delete")
public void deleteZip(String zipPath){
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();//D:/ruoyi/uploadPath/upload
String path = filePath+RESUME_ZIP_MKDIR+zipPath;
File file = new File(path);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean delete = file.delete();
}