springboot实现文件上传下载

wapConfig.getFilePath()配置文件存储的本地地址(例如:D:\xxFiles\)

上传文件需要判断文件夹是否存在,文件路径如果是a/b/c的则需要创建多个文件夹,判断如果存在,需要删除之前的文件,转存覆盖文件

  • 上传单个文件
    @ApiOperation(value = "上传文件")
    @PostMapping("uploadFile/{path}")
    public WapResponse<String> uploadFile(@RequestParam String path, @RequestParam MultipartFile file) throws IOException {
        try {
            String rootPath = wapConfig.getFilePath();
            File folder = new File(rootPath);
            if (!folder.exists()) {//判断文件夹是否存在
                folder.mkdir();
            }
            if (path != null) {//如果路径是多层则需要循环创建文件夹
                String[] folderNames = path.split("/");
                for (int i = 0; i < folderNames.length; i++) {
                    rootPath = rootPath + "\\" + folderNames[i];
                    File folderFile = new File(rootPath);
                    if (!folderFile.exists()) {//判断文件夹是否存在
                        folderFile.mkdir();//创建文件夹
                    }
                }
            }

            String filename = file.getOriginalFilename();//获取文件名
            String filePath = rootPath + "\\" + filename;//文件的绝对路径
            File newFile=new File(filePath);
            if(newFile.exists())//判断是否存在
                newFile.delete();//删除旧的文件
            file.transferTo(newFile);//文件转存
            return WapResponse.success(filePath);
        } catch (Exception e) {
            log.error(e.getMessage());
            return WapResponse.error();
        }
    }
  • 上传文件集合
    @ApiOperation(value = "上传文件集合")
    @PostMapping("uploadFileList/{path}")
    public WapResponse<ArrayList<String>> uploadFileList(@RequestPart String path, @RequestParam MultipartFile[] files) throws IOException {
        try {
            String rootPath = wapConfig.getFilePath();
            File folder = new File(rootPath);
            if (!folder.exists()) {//判断文件夹是否存在
                folder.mkdir();
            }
            if (path != null) {//循环创建文件夹
                String[] folderNames = path.split("/");
                for (int i = 0; i < folderNames.length; i++) {
                    rootPath = rootPath + "\\" + folderNames[i];
                    File folderFile = new File(rootPath);
                    if (!folderFile.exists()) {//判断文件夹是否存在
                        folderFile.mkdir();
                    }
                }
            }
            ArrayList<String> filePaths = new ArrayList<>();
            for (MultipartFile file : files) {
                String filename = file.getOriginalFilename();//获取文件名
                String filePath = rootPath + "\\" + filename;//创建文件的绝对路径
                file.transferTo(new File(filePath));//文件转存
                filePaths.add(filePath);
            }
            return WapResponse.success(filePaths);
        } catch (Exception e) {
            log.error(e.getMessage());
            return WapResponse.error();
        }
    }

文件太多需要压缩成一个包下载,新建了一个压缩的工具类

import lombok.extern.slf4j.Slf4j;
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

import java.io.*;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;

/**
 * @author ssx
 * @data 2022/5/21 16:57
 * info:压缩解压工具类
 */
@Slf4j
public class UnPackeUtil {

    /**
     * 不加密的压缩
     * @param inputFile D:\\test  要打包的文件夹
     * @param outputFile  D:\test.zip  生成的压缩包的名字
     */
    public static void zipFile(String inputFile,String outputFile)  {
        // 生成的压缩文件
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(outputFile);
            ZipParameters parameters = new ZipParameters();
            // 压缩方式
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            // 压缩级别
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            // 要打包的文件夹
            File currentFile = new File(inputFile);
            File[] fs = currentFile.listFiles();
            // 遍历test文件夹下所有的文件、文件夹
            for (File f : fs) {
                if (f.isDirectory()) {
                    zipFile.addFolder(f.getPath(), parameters);
                } else {
                    zipFile.addFile(f, parameters);
                }
            }
        } catch (ZipException e) {
            e.printStackTrace();
        }

    }

    /**
     * zip文件解压
     *
     * @param destPath 解压文件路径
     * @param zipFile  压缩文件
     */
    public static void unPackZip(File zipFile, String destPath) {
        try {
            ZipFile zip = new ZipFile(zipFile);
            /*zip4j默认用GBK编码去解压,这里设置编码为GBK的*/
            zip.setFileNameCharset("GBK");
            log.info("begin unpack zip file....");
            zip.extractAll(destPath);

        } catch (Exception e) {
            log.error("解压失败:", e.getMessage(), e);
        }
    }

    /**
     * rar文件解压(不支持有密码的压缩包)
     *
     * @param rarFile  rar压缩包
     * @param destPath 解压保存路径
     */
    public static void unPackRar(File rarFile, String destPath) {
        try (Archive archive = new Archive(rarFile)) {
            if (null != archive) {
                FileHeader fileHeader = archive.nextFileHeader();
                File file = null;
                while (null != fileHeader) {
                    // 防止文件名中文乱码问题的处理
                    String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader.getFileNameString() : fileHeader.getFileNameW();
                    if (fileHeader.isDirectory()) {
                        //是文件夹
                        file = new File(destPath + File.separator + fileName);
                        file.mkdirs();
                    } else {
                        //不是文件夹
                        file = new File(destPath + File.separator + fileName.trim());
                        if (!file.exists()) {
                            if (!file.getParentFile().exists()) {
                                // 相对路径可能多级,可能需要创建父目录.
                                file.getParentFile().mkdirs();
                            }
                            file.createNewFile();
                        }
                        FileOutputStream os = new FileOutputStream(file);
                        archive.extractFile(fileHeader, os);
                        os.close();
                    }
                    fileHeader = archive.nextFileHeader();
                }
            }
        } catch (Exception e) {
            log.error("解压失败:", e.getMessage(), e);
        }
    }


    public static ZipOutputStream zipFiles1(List<String> fileList,String rootPath) throws IOException {
        // 文件的压缩包路径
        String zipPath = rootPath+System.currentTimeMillis()+".zip";
        // 获取文件压缩包输出流
        try (OutputStream outputStream = new FileOutputStream(zipPath);
             CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream,new Adler32());
             ZipOutputStream zipOut = new ZipOutputStream(checkedOutputStream)){
            for (String fileName : fileList) {
                String filePath=rootPath+fileName;
                File file=new File(filePath);
                // 获取文件输入流
                InputStream fileIn = new FileInputStream(file);
                // 使用 common.io中的IOUtils获取文件字节数组
                byte[] bytes = IOUtils.toByteArray(fileIn);
                // 写入数据并刷新
                zipOut.putNextEntry(new ZipEntry(file.getName()));
                zipOut.write(bytes,0,bytes.length);
                zipOut.flush();
            }
            return zipOut;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String zipFiles(List<String> fileList,String rootPath) throws IOException {
        // 文件的压缩包路径
        String zipPath = rootPath+System.currentTimeMillis()+".zip";
        //这个是压缩之后的文件绝对路径
        FileOutputStream fos = new FileOutputStream(zipPath);
        ZipOutputStream zipOut = new ZipOutputStream(fos);
        for (String fileName : fileList) {
            String filePath = rootPath + fileName;
            File fileToZip = new File(filePath);
            zipFileList(fileToZip, fileToZip.getName(), zipOut);
        }
        zipOut.close();
        fos.close();
        return zipPath;
    }

    private static void zipFileList(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
        if (fileToZip.isHidden()) {
            return;
        }
        if (fileToZip.isDirectory()) {
            if (fileName.endsWith("/")) {
                zipOut.putNextEntry(new ZipEntry(fileName));
                zipOut.closeEntry();
            } else {
                zipOut.putNextEntry(new ZipEntry(fileName + "/"));
                zipOut.closeEntry();
            }
            File[] children = fileToZip.listFiles();
            for (File childFile : children) {
                zipFileList(childFile, fileName + "/" + childFile.getName(), zipOut);
            }
            return;
        }
        FileInputStream fis = new FileInputStream(fileToZip);
//        ZipEntry zipEntry = new ZipEntry(fileName);
//        zipOut.putNextEntry(zipEntry);
//        byte[] bytes = new byte[1024];
//        int length;
//        while ((length = fis.read(bytes)) >= 0) {
//            zipOut.write(bytes, 0, length);
//        }
        BufferedReader in=new BufferedReader(new InputStreamReader(fis,"GBK"));
        zipOut.putNextEntry(new ZipEntry(fileName));

        String temp;
        while((temp=in.readLine())!=null){
            zipOut.write(temp.getBytes("GBK"));
        }


        zipOut.closeEntry();
        fis.close();
    }
}
  • 单个文件下载
    @ApiOperation(value = "单个文件下载")
    @GetMapping("downOneFile/{fileName}")
    public WapResponse<File> downOneFile(@PathVariable String fileName) throws Exception {
        String rootPath = wapConfig.getFilePath();
        String filePath = rootPath + fileName;//filename是根节点后面的路径和文件名:a/b/c.txt
        File file = new File(filePath);
        return WapResponse.success(file);
    }
  • 多文件压缩包下载
    @PostMapping("downFileList")
    @ApiOperation(value = "多文件打包下载")
    public WapResponse<String> downFileList(@RequestBody List<String> fileNames) throws Exception {
        String rootPath = wapConfig.getFilePath();
        String zipPath = UnPackeUtil.zipFiles(fileNames, rootPath);
        return WapResponse.success(zipPath);
    }
  • 单文件压缩包下载
    @GetMapping("zipFile/{fileName}")
    @ApiOperation(value = "打包下载文件")
    public WapResponse<String> zipFile(@PathVariable String fileName) throws Exception {
        String rootPath = wapConfig.getFilePath()+fileName;
        String zipPath = rootPath + System.currentTimeMillis()+".zip";
        UnPackeUtil.zipFile(rootPath, zipPath);
        return WapResponse.success(zipPath);
    }

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姗姗的鱼尾喵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值