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 {
            //创建压缩文件对象
            zipFile = new ZipFile(oriFile);
            //开始解压
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                // 如果是文件夹,就创建个文件夹
                if (entry.isDirectory()) {
                    oriFile.mkdirs();
                } else {
                    // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    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 {
            // 关流顺序,先打开的后关闭
            try {
                if (fos != null) {
                    fos.close();
                }
                if (is != null) {
                    is.close();
                }
                if (zipFile != null) {
                    zipFile.close();
                }
            } catch (IOException e) {
                log.error("文件流关闭异常,{}", 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文件至服务器中")
    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具体业务

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作为文件夹新名称,不重复
        String zipName = newName + ".zip";//uuid作为压缩文件新名称,不重复
        //创建文件夹,今天的日期
        String date = MyDateUtils.parseDate2String(new Date());
        //文件存放位置,加一层日期
        String path = getUploadPath() + date;
        //返回结果
        Map<String, Object> pathMap = new HashMap<>();
        InputStream inputStream = null;//文件流
        try {
            inputStream = file.getInputStream();
            //检测创建文件夹
            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);
    }

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐