SpringBoot上传文件 MultipartFile

/**
 * @ClassName UploadFileUtil
 * @Description 文件上传
 * @Author leis
 * @Version 1.0
 **/
@Slf4j
public class UploadFileUtil {
    /**
     * 默认文件后缀
     */
    private static Set<String> fileSuffixSet = Sets.newHashSet(".jpg", ".jpeg", ".gif", ".png", ".bmp", ".tif");

    /**
     * 默认文件大小
     */
    private static long defaultFileSize = 5 * 1024 * 1024;

    /**
     * 默认文件上传路径
     * 限制必须上传文件路径
     */
    private static String defaultPath;


    /**
     * 上传单文件
     * 使用默认的上传地址
     *
     * @param fileSize      上传文件的大小限制
     * @param multipartFile 需要上传的文件
     * @return 文件上传的地址
     */
    public static Map<String, String> uploadFile(Long fileSize, MultipartFile multipartFile) throws IOException {
        defaultFileSize = fileSize;
        return uploadFile(multipartFile);
    }

    /**
     * 上传单文件
     *
     * @param uploadPath    需要上传的地址
     * @param fileSize      上传文件的大小限制
     * @param multipartFile 需要上传的文件
     * @return 文件上传的地址
     */
    public static Map<String, String> uploadFile(String uploadPath, Long fileSize, MultipartFile multipartFile) throws IOException {
        defaultFileSize = fileSize;
        return uploadFile(uploadPath, multipartFile);
    }

    /**
     * 上传单文件
     * 检查文件大小使用默认的最大配置
     *
     * @param uploadPath    需要上传的地址
     * @param multipartFile 需要上传的文件
     * @return 文件上传的地址
     */
    public static Map<String, String> uploadFile(String uploadPath, MultipartFile multipartFile) throws IOException {
        defaultPath = uploadPath;
        return uploadFile(multipartFile);
    }

    /**
     * 上传单文件
     * 检查文件大小使用默认的最大配置
     * 使用默认的地址
     *
     * @param multipartFile 上传的文件
     * @return map K-V
     * status 上传标记 S 成功 F 失败
     * path 上传成功返回路径
     * message 上传失败返回异常信息
     */
    private static Map<String, String> uploadFile(MultipartFile multipartFile) {
        Map<String, String> resultMaps = Maps.newConcurrentMap();
        resultMaps.put("status", "F");
        try {
            String suffix = checkFile(multipartFile);
            Preconditions.checkNotNull(defaultPath, "上传地址不能为空");
            File file = wrapFile(defaultPath, multipartFile.getOriginalFilename(), suffix);
            multipartFile.transferTo(file);
            log.info("************上传成功**********返回值:{}***", file.getPath());
            resultMaps.put("status", "S");
            resultMaps.put("path", file.getPath());
            return resultMaps;
        } catch (NullPointerException e) {
            log.error("*****checkFile******{}", e.getMessage());
            resultMaps.put("message", e.getMessage());
            return resultMaps;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("*****上传失败*****{}", e.getMessage());
            resultMaps.put("message", "上传失败");
            return resultMaps;
        } catch (IllegalArgumentException e) {
            log.error("*****checkFile*****{}", e.getMessage());
            resultMaps.put("message", e.getMessage());
            return resultMaps;
        }
    }

    /**
     * 生成上传的不重名文件
     *
     * @param path             上传路径
     * @param originalFilename 上传文件初始名称
     * @param suffix           上传文件后缀
     * @return 可以上传的不重名文件
     */
    private static File wrapFile(String path, String originalFilename, String suffix) {
        File file = new File(path + originalFilename);
        if (file.exists()) {
            String name = LocalDate.now().toString().replaceAll("-", "") + System.currentTimeMillis();
            originalFilename = name + "." + suffix;
        } else {
            return file;
        }
        return wrapFile(path, originalFilename, suffix);
    }

    /**
     * 检查文件是否符合需求
     *
     * @param multipartFile 需要上传的文件
     * @return 上传文件后缀
     * @throws NullPointerException
     * @throws IllegalArgumentException
     */
    private static String checkFile(MultipartFile multipartFile) throws NullPointerException, IllegalArgumentException {
        Preconditions.checkNotNull(multipartFile, "文件不能为空");
        Preconditions.checkArgument(multipartFile.getSize() < defaultFileSize, "上传文件不能超过5M");
        String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
        Preconditions.checkArgument(!fileSuffixSet.contains(suffix), "文件类型不正确");
        return suffix;
    }
}

需要的jar包 lombok guava

Classes contained in spring-mock.jar: org.springframework.mock.jndi.ExpectedLookupTemplate.class org.springframework.mock.jndi.SimpleNamingContext.class org.springframework.mock.jndi.SimpleNamingContextBuilder.class org.springframework.mock.web.DelegatingServletInputStream.class org.springframework.mock.web.DelegatingServletOutputStream.class org.springframework.mock.web.HeaderValueHolder.class org.springframework.mock.web.MockExpressionEvaluator.class org.springframework.mock.web.MockFilterChain.class org.springframework.mock.web.MockFilterConfig.class org.springframework.mock.web.MockHttpServletRequest.class org.springframework.mock.web.MockHttpServletResponse.class org.springframework.mock.web.MockHttpSession.class org.springframework.mock.web.MockMultipartFile.class org.springframework.mock.web.MockMultipartHttpServletRequest.class org.springframework.mock.web.MockPageContext.class org.springframework.mock.web.MockRequestDispatcher.class org.springframework.mock.web.MockServletConfig.class org.springframework.mock.web.MockServletContext.class org.springframework.mock.web.PassThroughFilterChain.class org.springframework.mock.web.portlet.MockActionRequest.class org.springframework.mock.web.portlet.MockActionResponse.class org.springframework.mock.web.portlet.MockMultipartActionRequest.class org.springframework.mock.web.portlet.MockPortalContext.class org.springframework.mock.web.portlet.MockPortletConfig.class org.springframework.mock.web.portlet.MockPortletContext.class org.springframework.mock.web.portlet.MockPortletPreferences.class org.springframework.mock.web.portlet.MockPortletRequest.class org.springframework.mock.web.portlet.MockPortletRequestDispatcher.class org.springframework.mock.web.portlet.MockPortletResponse.class org.springframework.mock.web.portlet.MockPortletSession.class org.springframework.mock.web.portlet.MockPortletURL.class org.springframework.mock.web.portlet.MockRenderRequest.class org.springframework.mock.web.portlet.MockRenderResponse.class org.springframework.test.AbstractDependencyInjectionSpringContextTests.class org.springframework.test.AbstractSingleSpringContextTests.class org.springframework.test.AbstractSpringContextTests.class org.springframework.test.AbstractTransactionalDataSourceSpringContextTests.class org.springframework.test.AbstractTransactionalSpringContextTests.class org.springframework.test.AssertThrows.class org.springframework.test.ConditionalTestCase.class org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.class org.springframework.test.annotation.DirtiesContext.class org.springframework.test.annotation.ExpectedException.class org.springframework.test.annotation.IfProfileValue.class org.springframework.test.annotation.NotTransactional.class org.springframework.test.annotation.ProfileValueSource.class org.springframework.test.annotation.Repeat.class org.springframework.test.annotation.SystemProfileValueSource.class org.springframework.test.annotation.Timed.class org.springframework.test.jpa.AbstractAspectjJpaTests.class org.springframework.test.jpa.AbstractJpaTests.class org.springframework.test.jpa.OrmXmlOverridingShadowingClassLoader.class org.springframework.test.web.AbstractModelAndViewTests.class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

BananaNo2

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

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

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

打赏作者

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

抵扣说明:

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

余额充值