最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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)文章

  • JavaWeb項目中JSP訪問的問題解決

    JavaWeb項目中JSP訪問的問題解決

    JSP文件一般有兩個存放位置,本文主要介紹了JavaWeb項目中JSP訪問的問題解決,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • Java 二叉樹遍歷特別篇之Morris遍歷

    Java 二叉樹遍歷特別篇之Morris遍歷

    二叉樹的遍歷(traversing binary tree)是指從根結(jié)點出發(fā),按照某種次序依次訪問二叉樹中所有的結(jié)點,使得每個結(jié)點被訪問依次且僅被訪問一次。四種遍歷方式分別為:先序遍歷、中序遍歷、后序遍歷、層序遍歷
    2021-11-11
  • 解決SpringSecurity 一直登錄失敗的問題

    解決SpringSecurity 一直登錄失敗的問題

    這篇文章主要介紹了解決SpringSecurity 一直登錄失敗的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • Java多線程模擬銀行系統(tǒng)存錢問題詳解

    Java多線程模擬銀行系統(tǒng)存錢問題詳解

    本文將利用Java多線程模擬一個簡單的銀行系統(tǒng),使用兩個不同的線程向同一個賬戶存錢。文中的示例代碼講解詳細(xì),感興趣的可以了解一下
    2022-09-09
  • Spring高級注解@PropertySource詳細(xì)解讀

    Spring高級注解@PropertySource詳細(xì)解讀

    這篇文章主要介紹了Spring高級注解@PropertySource詳細(xì)解讀,@PropertySource注解用于指定資源文件讀取的位置,它不僅能讀取properties文件,也能讀取xml文件,并且通過YAML解析器,配合自定義PropertySourceFactory實現(xiàn)解析yaml文件,需要的朋友可以參考下
    2023-11-11
  • SpringMVC 限流的示例代碼

    SpringMVC 限流的示例代碼

    這篇文章主要介紹了SpringMVC 限流的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12
  • java實現(xiàn)學(xué)生宿舍系統(tǒng)

    java實現(xiàn)學(xué)生宿舍系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了java實現(xiàn)學(xué)生宿舍系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • Java多線程Runable售票系統(tǒng)實現(xiàn)過程解析

    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日)

    這篇文章主要介紹了IntelliJ IDEA 2018 最新激活碼(截止到2018年1月30日)的相關(guān)資料,需要的朋友可以參考下
    2018-01-01
  • 將java項目打包成exe可執(zhí)行文件的完整步驟

    將java項目打包成exe可執(zhí)行文件的完整步驟

    最近項目要求,需要將java項目生成exe文件,下面這篇文章主要給大家介紹了關(guān)于如何將java項目打包成exe可執(zhí)行文件的相關(guān)資料,文章通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2022-06-06

最新評論

广汉市| 礼泉县| 金坛市| 义乌市| 孟州市| 宜章县| 九江县| 富源县| 贵阳市| 南投县| 政和县| 湟中县| 射阳县| 梅河口市| 张掖市| 界首市| 儋州市| 广汉市| 文成县| 井研县| 西和县| 高雄县| 白玉县| 临武县| 新乡县| 长岭县| 佳木斯市| 烟台市| 中江县| 惠州市| 林州市| 乌拉特前旗| 临汾市| 安康市| 阿合奇县| 南溪县| 万宁市| 偏关县| 永德县| 皋兰县| 英山县|