Java springboot壓縮文件上傳,解壓,刪除壓縮包方式
Java springboot壓縮文件上傳,解壓,刪除壓縮包
1. 配置文件
在application.yml里
file-server: path: \material-main\ # 自己隨便命名。注意,不管windows還是linux,路徑不需要帶盤符,用代碼去識別即可
2. 工具類
如果需要?jiǎng)h除壓縮包,把下邊的注釋解開
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)建個(gè)文件夾
if (entry.isDirectory()) {
oriFile.mkdirs();
} else {
// 如果是文件,就先創(chuàng)建一個(gè)文件,然后用io流把內(nèi)容copy過去
File targetFile = new File(destDirPath + "/" + entry.getName());
// 保證這個(gè)文件的父文件夾必須要存在
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 將壓縮文件內(nèi)容寫入到這個(gè)文件中
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() {//智能識別補(bǔ)全路徑
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會取第一個(gè)盤盤符
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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決Mybatis?mappe同時(shí)傳遞?List?和其他參數(shù)報(bào)錯(cuò)的問題
在使用MyBatis時(shí),如果需要傳遞多個(gè)參數(shù)到SQL中,可以遇到參數(shù)綁定問題,解決方法包括使用@Param注解和修改mapper.xml配置,感興趣的朋友跟隨小編一起看看吧2024-09-09
Java服務(wù)端性能優(yōu)化之JVM垃圾回收策略詳解
JVM垃圾回收策略涵蓋了基本原理、常見策略(如SerialGC、ParallelGC、CMS、G1GC)以及優(yōu)化建議,選擇合適的策略和調(diào)整參數(shù),如堆大小和GC日志,可以提高應(yīng)用性能和響應(yīng)速度,持續(xù)監(jiān)控和分析是關(guān)鍵步驟2025-03-03
springboot整合RabbitMQ中死信隊(duì)列的實(shí)現(xiàn)
死信是無法被消費(fèi)的消息,產(chǎn)生原因包括消息TTL過期、隊(duì)列最大長度達(dá)到以及消息被拒絕且不重新排隊(duì),RabbitMQ的死信隊(duì)列機(jī)制能夠有效防止消息數(shù)據(jù)丟失,適用于訂單業(yè)務(wù)等場景,本文就來介紹一下2024-10-10
java實(shí)現(xiàn)省市區(qū)三級聯(lián)動
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)省市區(qū)三級聯(lián)動,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06
解析Java的Spring框架的BeanPostProcessor發(fā)布處理器
這篇文章主要介紹了Java的Spring框架的BeanPostProcessor發(fā)布處理器,Spring是Java的SSH三大web開發(fā)框架之一,需要的朋友可以參考下2015-12-12
詳解SpringBoot中使用JPA作為數(shù)據(jù)持久化框架
這篇文章主要介紹了SpringBoot中使用JPA作為數(shù)據(jù)持久化框架的相關(guān)知識,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03

