spring上传文件返回绝对路径,简单工具类

本文详细介绍了一种使用SpringBoot框架进行文件上传的方法,通过MultipartFile接口和自定义的文件名生成策略,实现了文件的高效上传及路径返回。文章深入探讨了如何创建上传目录、生成唯一文件名以及处理上传过程中的异常情况。
import com.google.common.io.Files;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


/**
 * @Auther: zyx.
 * @Date: 2018/12/17 8:55
 */
@Slf4j
public class UploadFileUtils {

    /**
     * 上传单个文件,文件命名以
     * 20181215T180946598
     * 加后缀为列
     * 返回文件路径
     *
     * @param: [file, uploadFilePath]
     * @return: java.lang.String
     * @date: 2018/12/17 9:14
     */
    public static String upload(MultipartFile file, String uploadFilePath) {
        if (null == file) {
            return null;
        }
        String originalFileName = file.getOriginalFilename();
        String fileExtension = Files.getFileExtension(originalFileName);

        // create upload directory if not exist
        createUploadDirIfNotExist(uploadFilePath);

        String newFileAbsolutePath = generateFileAbsolutePath(uploadFilePath, fileExtension);
        try {
            file.transferTo(new File(newFileAbsolutePath));
        } catch (IOException e) {
            log.error("upload file error ", e);
            return null;
        }
        return newFileAbsolutePath;
    }

    /**
     * create upload directory if not exist.
     *
     * @param uploadFilePath upload directory
     */
    private static void createUploadDirIfNotExist(String uploadFilePath) {
        File uploadDir = new File(uploadFilePath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
    }
/**
 * absolute file root path + current time("yyyyMMdd'T'HHmmssSSS")
 *
 * @see DateUtils#T_PATTERN
 */
public static String generateFileAbsolutePath(String uploadDir, String fileExtension) {
  // current time + "_" + generateId
  String newFileName = DateUtils.formatT();
  newFileName = uploadDir.concat(newFileName).concat(".").concat(fileExtension);

  return newFileName;
}

}

转载于:https://my.oschina.net/zhangyaxin/blog/2990640

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值