• 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");
        }
    }

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

  • 相关阅读:
    【idea】批量修改文件的换行类型
    【shell】for循环执行sql语句
    【gitlab】创建token供外部git clone
    【idea】修改git源
    【浏览器】 NET::ERR_CERT_INVALID
    mac os 11 Big Sur 根目录无法写入解决办法
    dbeaver把表数据导出csv时字符串自动加双引号问题解决
    spring boot2 jpa分页查询百万级数据内存泄漏
    win10安装MAT并单独配置jdk11
    Transaction silently rolled back because it has been marked as rollback-only
  • 原文地址:https://www.cnblogs.com/qingmuchuanqi48/p/12052316.html
Copyright © 2020-2023  润新知