文件工具类

该文件提供了一系列静态方法,用于处理MultipartFile对象的保存、创建目录、创建文件、删除文件、检查文件是否存在以及计算文件的MD5值。主要应用场景包括上传文件的保存、文件路径处理和文件一致性验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、常用 

package com.hssmart.common.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * 文件工具类
 *
 * @author syh
 */
public class FileUtils {

    /**
     * 将MultipartFile保存到指定的路径下
     *
     * @param file Spring的MultipartFile对象
     * @param savePath 保存路径
     * @return 保存的文件名,当返回NULL时为保存失败。
     */
    public static String save(MultipartFile file, String savePath) {
        if (file != null && file.getSize() > 0) {
            File fileFolder = new File(savePath);
            // 目录不存在,创建目录
            if (!fileFolder.exists()) {
                fileFolder.mkdirs();
            }
            File saveFile = getFile(savePath, file.getOriginalFilename());
            try {
                file.transferTo(saveFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return saveFile.getName();
        }
        return null;
    }
    
    private static File getFile(String savePath, String originalFilename) {
        String fileName = System.currentTimeMillis() + "_" + originalFilename;
        File file = new File(savePath + fileName);
        if (file.exists()) {
            return getFile(savePath, originalFilename);
        }
        return file;
    }

    /***
     * @description 适用于自己项目的文件保存
     * @author syh
     * @date 2023/9/24 13:37
     * @param	multipartFiles  文件列表
     * @param	writePath  文件存储路径
     * @return 返回图片回显路径字符串,逗号拼接。否则返回空字符串
    */
    public static String multipartFileListSave(MultipartFile[] multipartFiles, String writePath) {
        if (multipartFiles!= null && multipartFiles.length != 0) {
            StringBuilder picturePath = new StringBuilder();
            for (MultipartFile pictureFile : multipartFiles) {
                String save = FilesUtils.save(pictureFile, writePath);
                int i = save.indexOf(":");
                if (i != -1) {
                    picturePath.append(save.substring(i + 1)).append(",");
                }
            }
            return picturePath.deleteCharAt(picturePath.length() - 1).toString();
        }
        return "";
    }

    /**
     * 创建多级文件夹
     *
     * @param savePath 文件路径
     * @return 创建文件是否成功
     */
    public static boolean createCatalogue(String savePath) {
        File fileFolder = new File(savePath);
        // 目录不存在,创建目录
        if (!fileFolder.exists()) {
            return fileFolder.mkdirs();
        } else {
            // 目录存在,直接返回true
            return true;
        }
    }
    
    /**
     * 创建文件
     *
     * @param filePath 文件路径
     * @return 创建文件是否成功
     */
    public static boolean createFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                return file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 删除文件
     *
     * @filePath  文件路径
     */
    public static boolean resultDelete(String filePath){
        File file = new File(filePath);
        if (file.isFile()){
            file.delete();
            return true;
        }else{
            return false;
        }
    }

    /**
     * 文件是否存在
     *
     * @param filePath 文件路径
     * @return 文件是否存在
     */
    public static boolean exists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    /**
     * MD5判断文件的正确性
     *
     * @return 获取到的文件md5值
     */
    public static String getFileMD5(File file) throws IOException {
        if (!file.exists() || !file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[8192];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            BigInteger bigInt = new BigInteger(1, digest.digest());
            return bigInt.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            in.close();
        }
    }
}

二、File与MultipartFile互转

 File转MultipartFile

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.2</version>
</dependency>
    /***
     * @MethodName getMultipartFile
     * @Description  File转MultipartFile
     * @param file File类
     * @param fieldName  生成的文件名称
     * @return org.apache.commons.fileupload.FileItem
     *
     * @Author syh
     * @Date 2023/4/14 15:01
     */
    public static FileItem getMultipartFile(File file, String fieldName){
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
FileItem fileItem  = FileUploading.getMultipartFile(file, System.currentTimeMillis() + zcLidInfo.getId());
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

MultipartFile转File

    /**
     * 将MultipartFile转换为File
     * @param multiFile  MultipartFile对象
     * @return File对象
     */
    public static File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

三、Base64与MultipartFile互转 

Base64转MultipartFile

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

public static MultipartFile base64ToMultipartFile (String s) {
        MultipartFile image = null;
        StringBuilder base64 = new StringBuilder("");
        if (s != null && !"".equals(s)) {
            base64.append(s);
            String[] baseStrs = base64.toString().split(",");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            try {
                b = decoder.decodeBuffer(baseStrs[1]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (int j = 0; j < b.length; ++j) {
                if (b[j] < 0) {
                    b[j] += 256;
                }
            }
            image = new  BASE64DecodedMultipartFile(b, baseStrs[0]);
        }
        return image;
    }
package com.hssmartcity.common.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @ClassName BASE64DecodedMultipartFile
 * @Description TODO
 * @Author syh
 * @Date 2023/8/7 10:48
 */
public class BASE64DecodedMultipartFile implements MultipartFile {

    private final byte[] imgContent;
    private final String header;

    public BASE64DecodedMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imgContent);
    }

}

MultipartFile转Base64

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.IOException;

/**
 * @ClassName FilesUtils
 * @Description 文件工具类
 * @Author syh
 * @Date 2023/9/13 14:40
 */
public class FilesUtils {

    /**
     * 将MultipartFile 图片文件编码为base64
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String generateBase64(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("图片不能为空!");
        }
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String contentType = file.getContentType();
        byte[] imageBytes = null;
        String base64EncoderImg = "";
        try {
            imageBytes = file.getBytes();
            BASE64Encoder base64Encoder = new BASE64Encoder();
            /**
             * 1.Java使用BASE64Encoder 需要添加图片头("data:" + contentType + ";base64,"),
             *   其中contentType是文件的内容格式。
             * 2.Java中在使用BASE64Enconder().encode()会出现字符串换行问题,这是因为RFC 822中规定,
             *   每72个字符中加一个换行符号,这样会造成在使用base64字符串时出现问题,
             *   所以我们在使用时要先用replaceAll("[\\s*\t\n\r]", "")解决换行的问题。
             */
            base64EncoderImg = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes);
            base64EncoderImg = base64EncoderImg.replaceAll("[\\s*\t\n\r]", "");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return base64EncoderImg;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

S Y H

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

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

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

打赏作者

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

抵扣说明:

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

余额充值