springboot文件操作工具类

本文档介绍了FileUtils工具类,用于处理文件上传、创建唯一文件名、解析文件类型和下载路径,提升开发效率。

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

package com.oasys.utils;

import com.oasys.ecxeption.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件工具类
 */
public final class FileUtils {

    private static final Logger log = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 存放位置:简历
     */
    public static final String STORAGE_LOCATION_RESUME = "saveFiles/resume/";

    /**
     * 存放位置:发票
     */
    public static final String STORAGE_LOCATION_RECEIPT = "saveFiles/receipt/";

    public static String createFileName(String location, String fileType) {
        if (StringUtils.isAnyBlank(location, fileType)) {
            throw new BusinessException("文件类型不可以为空哦");
        }
        try {
            return getBasePath() + location + getUuidFileName(fileType);
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("生成文件名失败, " + e.getMessage());
        }
    }

    public static String resolveFileType(MultipartFile multipartFile) {
        try {
            byte[] bytes = multipartFile.getBytes();
            if (bytes.length == 0) {
                throw new BusinessException("文件为空");
            }

            StringBuilder hexBuilder = new StringBuilder();
            for (byte aByte : bytes) {
                String hex = Integer.toHexString(aByte & 0xFF);
                if (hex.length() < 2) {
                    hexBuilder.append("0");
                }
                hexBuilder.append(hex);
                if (hexBuilder.length() > 30) {
                    break;
                }
            }
            String header = hexBuilder.toString().toUpperCase();

            String fileType = null;
            for (Map.Entry<String, String> entry : FILE_TYPE_MAP.entrySet()) {
                if (header.startsWith(entry.getKey())) {
                    fileType = entry.getValue();
                    break;
                }
            }

            if (fileType == null) {
                throw new BusinessException("不支持的文件类型");
            }

            return fileType;
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("解析文件失败, " + e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("解析文件失败");
        }

    }

    public static void saveFile(String fileName, MultipartFile multipartFile) {
        try {
            multipartFile.transferTo(new File(fileName));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("文件保存失败");
        }
    }

    public static String createDownloadUri(String location) {
        if (StringUtils.isAnyBlank(location)) {
            throw new BusinessException("生成下载路径失败, 文件路径为空");
        }
        try {
            return "/" + location.replace(getBasePath(), "");
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("生成下载路径失败, " + e.getMessage());
        }
    }

    private static String getUuidFileName(String fileType) {
        return UUID.randomUUID().toString().replace("-", "") + "." + fileType;
    }

    private static String getBasePath() {
        try {
            return ResourceUtils.getURL("classpath:").getPath();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("获取文件保存路径失败");
        }
    }

    private FileUtils() {}

    private static final Map<String, String> FILE_TYPE_MAP = new HashMap<>();

    static {
        FILE_TYPE_MAP.put("255044462d312e".toUpperCase(), "pdf");
        FILE_TYPE_MAP.put("504b0304140006000800".toUpperCase(), "docx");
        FILE_TYPE_MAP.put("d0cf11e0a1b11ae10000".toUpperCase(), "doc");
        FILE_TYPE_MAP.put("FFD8FF".toUpperCase(), "jpg");
        FILE_TYPE_MAP.put("89504E47".toUpperCase(), "png");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值