Java 多个文件生成zip包、下载zip包
一、文件上传
代码实现
/**
* 点击按钮 文件上传
*/
@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file){
String upload = fileService.upload(file);
System.out.println("upload:"+upload);
return "上传成功对应路径:"+upload;
}
public String upload(MultipartFile file){
//上传路径
String path = "D:\\var\\file\\uploadFile"+"\\"+file.getOriginalFilename();
String fileSavePath = null;
try {
boolean upload = this.saveFileUpload(path, this.multipartFileToFile(file));
if (upload) {
fileSavePath = path;
}
} catch (Exception e) {
log.error("文件上传失败,", e);
}
return fileSavePath;
}
/**
*
* @param savePath 保存路径
* @param file
* @return
*/
public boolean saveFileUpload(String savePath, File file) {
try {
if (StringUtils.isEmpty(savePath)) {
log.info("savePath is null");
return false;
}
log.info("save file path : " + savePath);
java.nio.file.Files.copy(file.toPath(), new File(savePath).toPath());
return true;
} catch (IOException e) {
log.error("saveFileUpload error", e);
}
return false;
}
/**
* MultipartFile 转 File
*/
public File multipartFileToFile(MultipartFile file) {
File toFile = null;
try{
if (file == null || StringUtils.isEmpty(file.getOriginalFilename()) || file.getSize() <= 0) {
return null;
} else {
InputStream ins;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
}catch (Exception e){
log.error("multipartFileToFile err", e);
}
return toFile;
}
/**
* 获取文件流
*/
private void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
结果展示
二、多个文件打成zip包
代码实现
@PostMapping("/yaZipFile")
public String yaZipFile() {
fileService.yaZipFile();
return "压缩成功";
}
路径
可以从前端传过来
public void yaZipFile() {
try {
//进行压缩
boolean b = FileDownloadUtils.generateFile("D:\\var\\file\\uploadFile", "zip", "D:\\var\\file", "uploadFiles");
if(b){
log.info("压缩成功....");
File sourceFile = new File("D:\\var\\file\\uploadFile");
boolean flag = FileDownloadUtils.deleteDir(sourceFile);
if(flag){
log.info("删除成功.....");
}
}
}catch (Exception e){
log.error("发生异常error:{}",e);
}
}
/**
* @param path 要压缩的文件路径
* @param format 生成的格式(zip、rar)
* @param zipPath zip的路径
* @param zipName zip文件名
* @Description 将多个文件进行压缩到指定位置
*/
public static boolean generateFile(String path, String format, String zipPath, String zipName) throws Exception {
File file = new File(path);
// 压缩文件的路径不存在
if (!file.exists()) {
throw new Exception("路径 " + path + " 不存在文件,无法进行压缩...");
}
// 用于存放压缩文件的文件夹
String generateFile = zipPath + File.separator;
File compress = new File(generateFile);
// 如果文件夹不存在,进行创建
if (!compress.exists()) {
compress.mkdirs();
}
// 目的压缩文件
String generateFileName = compress.getAbsolutePath() + File.separator + zipName + "." + format;
// 输出流
FileOutputStream outputStream = new FileOutputStream(generateFileName);
// 压缩输出流
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));
//压缩
generateFile(zipOutputStream, file, "");
System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的压缩文件生成位置:" + generateFileName);
// 关闭 输出流
zipOutputStream.close();
return true;
}
/**
* @param out 输出流
* @param file 目标文件
* @param dir 文件夹
* @throws Exception
*/
private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception {
// 当前的是文件夹,则进行一步处理
if (file.isDirectory()) {
//得到文件列表信息
File[] files = file.listFiles();
//将文件夹添加到下一级打包目录
out.putNextEntry(new ZipEntry(dir + "/"));
dir = dir.length() == 0 ? "" : dir + "/";
//循环将文件夹中的文件打包
for (int i = 0; i < files.length; i++) {
generateFile(out, files[i], dir + files[i].getName());
}
} else { // 当前是文件
// 输入流
FileInputStream inputStream = new FileInputStream(file);
// 标记要打包的条目
out.putNextEntry(new ZipEntry(dir));
// 进行写操作
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) > 0) {
out.write(bytes, 0, len);
}
// 关闭输入流
inputStream.close();
}
}
结果展示:
压缩包生成,把之前的目录删除
三、文件下载
代码实现
@PostMapping("/downZipFile")
public String downZipFile(HttpServletResponse response){
fileService.downZipFile(response);
return "下载成功";
}
路径、文件名
也可以从前端传过来
public void downZipFile(HttpServletResponse response){
String title = "uploadFiles.zip";
//压缩文件路径 D:\var\file
File filePath = new File("D:\\var\\file" + File.separator + title);
String filename = System.currentTimeMillis()+"_"+title;
//设置文件路径
if (filePath.exists()) {
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
//设置下载文件类型
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
byte[] buffer = new byte[4096];
fis = new FileInputStream(filePath);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
// 删除临时文件
filePath.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
结果展示
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/121428.html