Java springboot壓縮文件上傳,解壓,刪除壓縮包方式
更新時間:2025年04月21日 08:57:10 作者:葉梓啊
這篇文章主要介紹了Java springboot壓縮文件上傳,解壓,刪除壓縮包方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
Java springboot壓縮文件上傳,解壓,刪除壓縮包
1. 配置文件
在application.yml里
file-server: path: \material-main\ # 自己隨便命名。注意,不管windows還是linux,路徑不需要帶盤符,用代碼去識別即可
2. 工具類
如果需要刪除壓縮包,把下邊的注釋解開
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
@Slf4j
public class UnzipUtils {
/**
* 傳文件絕對路徑
*/
public static void zipUncompress(String inputFile) {
log.info("UnzipUtils開始解壓");
File oriFile = new File(inputFile);
// 判斷源文件是否存在
String destDirPath = inputFile.replace(".zip", "");
FileOutputStream fos = null;
InputStream is = null;
ZipFile zipFile = null;
try {
//創(chuàng)建壓縮文件對象
zipFile = new ZipFile(oriFile);
//開始解壓
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
// 如果是文件夾,就創(chuàng)建個文件夾
if (entry.isDirectory()) {
oriFile.mkdirs();
} else {
// 如果是文件,就先創(chuàng)建一個文件,然后用io流把內(nèi)容copy過去
File targetFile = new File(destDirPath + "/" + entry.getName());
// 保證這個文件的父文件夾必須要存在
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 將壓縮文件內(nèi)容寫入到這個文件中
is = zipFile.getInputStream(entry);
fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
}
}
} catch (Exception e) {
log.error("文件解壓過程中異常,{}", e);
} finally {
// 關(guān)流順序,先打開的后關(guān)閉
try {
if (fos != null) {
fos.close();
}
if (is != null) {
is.close();
}
if (zipFile != null) {
zipFile.close();
}
} catch (IOException e) {
log.error("文件流關(guān)閉異常,{}", e);
}
}
//解壓后刪除文件
// if (oriFile.exists()) {
// System.gc();
// oriFile.delete();
// if (oriFile.exists()) {
// System.gc();
// oriFile.delete();
// if (oriFile.exists()) {
// log.error("文件未被刪除");
// }
// }
// }
log.info("UnzipUtils解壓完成");
}
}
3. 使用
controller層。注意,我用的swagger3,也就是springdoc。
用swagger2(springfox)的,寫法沒這么麻煩
package com.mods.browser.controller;
import com.mods.browser.service.IFilesService;
import com.mods.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/files")
@Tag(name = "FilesController", description = "文件管理")
public class FilesController {
@Autowired
private IFilesService filesService;
//swagger3寫法
@PostMapping(value = "/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "上傳zip文件至服務(wù)器中")
public Result uploadFile(@RequestPart("file") MultipartFile file) {
return filesService.uploadFile(file);
}
// swagger2寫法
// @ApiOperation("上傳zip文件")
// @PostMapping("/file/upload")
// public Result uploadFile(MultipartFile file) {
// return filesService.uploadFile(file);
// }
}
service具體業(yè)務(wù)
package com.mods.browser.service.impl;
import com.mods.browser.service.IFilesService;
import com.mods.common.exception.CommonException;
import com.mods.common.result.Result;
import com.mods.common.result.ResultCode;
import com.mods.common.utils.FileUtils;
import com.mods.common.utils.MyDateUtils;
import com.mods.common.utils.UnzipUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
@Service
@Slf4j
public class FilesServiceImpl implements IFilesService {
@Value("${file-server.path}")
private String uploadPath;
private String getUploadPath() {//智能識別補全路徑
Properties props = System.getProperties();
String property = props.getProperty("os.name");
String userHomePath = props.getProperty("user.home");
String filePath = "";//文件存放地址
if (property.contains("Windows")) {
String[] arr = userHomePath.split(":");
String pan = arr[0] + ":";//windows會取第一個盤盤符
filePath = pan + uploadPath;
} else if (property.contains("Linux")) {
filePath = uploadPath;
}
return filePath;
}
@Override
public Result uploadFile(MultipartFile file) {
String originalFilename = file.getOriginalFilename();//原始名稱
if (StringUtils.isBlank(originalFilename) || !originalFilename.endsWith(".zip")) {
return new Result(ResultCode.FILE_WRONG);
}
String newName = UUID.randomUUID().toString().replace("-", "");//uuid作為文件夾新名稱,不重復(fù)
String zipName = newName + ".zip";//uuid作為壓縮文件新名稱,不重復(fù)
//創(chuàng)建文件夾,今天的日期
String date = MyDateUtils.parseDate2String(new Date());
//文件存放位置,加一層日期
String path = getUploadPath() + date;
//返回結(jié)果
Map<String, Object> pathMap = new HashMap<>();
InputStream inputStream = null;//文件流
try {
inputStream = file.getInputStream();
//檢測創(chuàng)建文件夾
Path directory = Paths.get(path);
if (!Files.exists(directory)) {
Files.createDirectories(directory);
}
Long size = Files.copy(inputStream, directory.resolve(zipName));//上傳文件,返回值是文件大小
pathMap.put("zip_size", size);
} catch (Exception e) {
pathMap.put("zip_size", 0);
return new Result(e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
throw new CommonException(e.getMessage());
}
}
String zipPath = path + File.separator + zipName;
UnzipUtils.zipUncompress(zipPath);
pathMap.put("main_path", zipPath);
pathMap.put("folder_path", path + File.separator + newName);
pathMap.put("zip_size_cent", "kb");
return new Result(pathMap);
}
@Override
public Result fileDel(String downloadPath) {
String absolutePath = FileUtils.getPathAndName(this.getUploadPath(), downloadPath);
boolean b = FileUtils.deleteFile(absolutePath);
return new Result(b);
}
}
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring高級注解@PropertySource詳細(xì)解讀
這篇文章主要介紹了Spring高級注解@PropertySource詳細(xì)解讀,@PropertySource注解用于指定資源文件讀取的位置,它不僅能讀取properties文件,也能讀取xml文件,并且通過YAML解析器,配合自定義PropertySourceFactory實現(xiàn)解析yaml文件,需要的朋友可以參考下2023-11-11
Java多線程Runable售票系統(tǒng)實現(xiàn)過程解析
這篇文章主要介紹了Java多線程Runable售票系統(tǒng)實現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06
IntelliJ IDEA 2018 最新激活碼(截止到2018年1月30日)
這篇文章主要介紹了IntelliJ IDEA 2018 最新激活碼(截止到2018年1月30日)的相關(guān)資料,需要的朋友可以參考下2018-01-01

