欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java springboot壓縮文件上傳,解壓,刪除壓縮包方式

 更新時(shí)間:2025年04月21日 08:57:10   作者:葉梓啊  
這篇文章主要介紹了Java springboot壓縮文件上傳,解壓,刪除壓縮包方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

Java springboot壓縮文件上傳,解壓,刪除壓縮包

1. 配置文件

在application.yml里

file-server:
  path: \material-main\
  # 自己隨便命名。注意,不管windows還是linux,路徑不需要帶盤(pán)符,用代碼去識(shí)別即可

2. 工具類(lèi)

如果需要?jiǎng)h除壓縮包,把下邊的注釋解開(kāi)

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 {

    /**
     * 傳文件絕對(duì)路徑
     */
    public static void zipUncompress(String inputFile) {
        log.info("UnzipUtils開(kāi)始解壓");
        File oriFile = new File(inputFile);
        // 判斷源文件是否存在
        String destDirPath = inputFile.replace(".zip", "");
        FileOutputStream fos = null;
        InputStream is = null;
        ZipFile zipFile = null;
        try {
            //創(chuàng)建壓縮文件對(duì)象
            zipFile = new ZipFile(oriFile);
            //開(kāi)始解壓
            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過(guò)去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保證這個(gè)文件的父文件夾必須要存在
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 將壓縮文件內(nèi)容寫(xiě)入到這個(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("文件解壓過(guò)程中異常,{}", e);
        } finally {
            // 關(guān)流順序,先打開(kāi)的后關(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)的,寫(xiě)法沒(méi)這么麻煩

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寫(xiě)法
    @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寫(xiě)法
//    @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() {//智能識(shí)別補(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會(huì)取第一個(gè)盤(pán)盤(pán)符
            filePath = pan + uploadPath;
        } else if (property.contains("Linux")) {
            filePath = uploadPath;
        }
        return filePath;
    }

    @Override
    public Result uploadFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();//原始名稱(chēng)
        if (StringUtils.isBlank(originalFilename) || !originalFilename.endsWith(".zip")) {
            return new Result(ResultCode.FILE_WRONG);
        }
        String newName = UUID.randomUUID().toString().replace("-", "");//uuid作為文件夾新名稱(chēng),不重復(fù)
        String zipName = newName + ".zip";//uuid作為壓縮文件新名稱(chēng),不重復(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();
            //檢測(cè)創(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)文章

  • Zookeeper ZkClient使用介紹

    Zookeeper ZkClient使用介紹

    ZkClient是Github上?個(gè)開(kāi)源的zookeeper客戶(hù)端,在Zookeeper原生API接口之上進(jìn)行了包裝,是?個(gè)更易用的Zookeeper客戶(hù)端,同時(shí),zkClient在內(nèi)部還實(shí)現(xiàn)了諸如Session超時(shí)重連、Watcher反復(fù)注冊(cè)等功能
    2022-09-09
  • 詳解Java 本地接口 JNI 使用方法

    詳解Java 本地接口 JNI 使用方法

    這篇文章主要介紹了詳解Java 本地接口 JNI 使用方法的相關(guān)資料,希望通過(guò)本文大家能徹底使用JNI編程,需要的朋友可以參考下
    2017-09-09
  • 解決Mybatis?mappe同時(shí)傳遞?List?和其他參數(shù)報(bào)錯(cuò)的問(wèn)題

    解決Mybatis?mappe同時(shí)傳遞?List?和其他參數(shù)報(bào)錯(cuò)的問(wèn)題

    在使用MyBatis時(shí),如果需要傳遞多個(gè)參數(shù)到SQL中,可以遇到參數(shù)綁定問(wèn)題,解決方法包括使用@Param注解和修改mapper.xml配置,感興趣的朋友跟隨小編一起看看吧
    2024-09-09
  • Java服務(wù)端性能優(yōu)化之JVM垃圾回收策略詳解

    Java服務(wù)端性能優(yōu)化之JVM垃圾回收策略詳解

    JVM垃圾回收策略涵蓋了基本原理、常見(jiàn)策略(如SerialGC、ParallelGC、CMS、G1GC)以及優(yōu)化建議,選擇合適的策略和調(diào)整參數(shù),如堆大小和GC日志,可以提高應(yīng)用性能和響應(yīng)速度,持續(xù)監(jiān)控和分析是關(guān)鍵步驟
    2025-03-03
  • 基于Java子線程中的異常處理方法(通用)

    基于Java子線程中的異常處理方法(通用)

    下面小編就為大家?guī)?lái)一篇基于Java子線程中的異常處理方法(通用)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-09-09
  • springboot整合RabbitMQ中死信隊(duì)列的實(shí)現(xiàn)

    springboot整合RabbitMQ中死信隊(duì)列的實(shí)現(xiàn)

    死信是無(wú)法被消費(fèi)的消息,產(chǎn)生原因包括消息TTL過(guò)期、隊(duì)列最大長(zhǎng)度達(dá)到以及消息被拒絕且不重新排隊(duì),RabbitMQ的死信隊(duì)列機(jī)制能夠有效防止消息數(shù)據(jù)丟失,適用于訂單業(yè)務(wù)等場(chǎng)景,本文就來(lái)介紹一下
    2024-10-10
  • java實(shí)現(xiàn)省市區(qū)三級(jí)聯(lián)動(dòng)

    java實(shí)現(xiàn)省市區(qū)三級(jí)聯(lián)動(dòng)

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)省市區(qū)三級(jí)聯(lián)動(dòng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-06-06
  • 解析Java的Spring框架的BeanPostProcessor發(fā)布處理器

    解析Java的Spring框架的BeanPostProcessor發(fā)布處理器

    這篇文章主要介紹了Java的Spring框架的BeanPostProcessor發(fā)布處理器,Spring是Java的SSH三大web開(kāi)發(fā)框架之一,需要的朋友可以參考下
    2015-12-12
  • java實(shí)現(xiàn)收藏名言語(yǔ)句臺(tái)詞的app

    java實(shí)現(xiàn)收藏名言語(yǔ)句臺(tái)詞的app

    本文給大家分享的是使用java制作的記錄名人名言臺(tái)詞等等讓你難忘的語(yǔ)句的APP的代碼,非常的實(shí)用,有需要的小伙伴可以參考下。
    2015-04-04
  • 詳解SpringBoot中使用JPA作為數(shù)據(jù)持久化框架

    詳解SpringBoot中使用JPA作為數(shù)據(jù)持久化框架

    這篇文章主要介紹了SpringBoot中使用JPA作為數(shù)據(jù)持久化框架的相關(guān)知識(shí),本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-03-03

最新評(píng)論