springboot中的照片上传工具类

public class UploadImgUtils {

    private static String savePath = "";

    /**
     * 上传照片工具类
     *
     * @param file     文件
     * @param workNo   工单号
     * @param property 配置的环境(dev,prod,test)
     * @return
     * @throws OperationException
     */
    public static String uploadImg(MultipartFile file, String workNo, String property) throws OperationException {
        if (file == null) {
            throw new OperationException(ReturnCodeEnum.OPERATION_IMG_IS_NULL);
        }
        if (file.getSize() > 1024 * 1024 * 1) {
            throw new OperationException(ReturnCodeEnum.OPERATION_IMG_SIZE_LARGE);
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            throw new OperationException(ReturnCodeEnum.OPERATION_IMG_FORM_ERROR);
        }
        //对savePath进行过赋值
        getProperties(property);
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录,则创建目录
            savePathFile.mkdir();
        }
        //用工单号作为唯一的标识符
        String filename = workNo + "." + suffix;
        try {
            //将文件保存指定目录
            file.transferTo(new File(savePath + filename));
        } catch (Exception e) {
            throw new OperationException(e, ReturnCodeEnum.OPERATION_SAVE_IMG_ERROR);
        }
        //返回文件名称
        return savePath + filename;
    }

    /**
     * 读取配置文件中的信息.
     *
     * @return
     */
    private static void getProperties(String name) {
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        factoryBean.setResources(new ClassPathResource("application-" + name + ".yml"));
        factoryBean.afterPropertiesSet();
        Properties object = factoryBean.getObject();
        savePath = (String) object.get("operation.savePath");
    }
}

上面的上传文件,下面的方法是用来获取环境变量的配置文件

你可能感兴趣的:(springboot中的照片上传工具类)