| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- package com.mokasz.sample.common.util;
- import cn.hutool.core.date.DatePattern;
- import cn.hutool.core.date.DateUtil;
- import cn.hutool.core.io.FileUtil;
- import com.mokasz.sample.common.constant.MimeTypeConstant;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.util.ResourceUtils;
- import org.springframework.web.multipart.MultipartFile;
- import java.io.File;
- import java.util.Date;
- /**
- * 文件上传工具类
- *
- * @author ljj12094
- */
- @Slf4j
- public class OssUtils {
- /**
- * 上传
- *
- * @param file 文件内容
- * @param domain 文件访问域名
- * @param path 文件保存路径
- * @return 文件地址
- */
- public static String upload(MultipartFile file, String domain, String path) {
- String filename;
- try {
- filename = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN) + getExtension(file, true);
- String filePath = ResourceUtils.getURL("classpath:").getPath() + path;
- File dest = new File(filePath, filename);
- // 拷贝文件到指定路径储存
- file.transferTo(dest);
- } catch (Exception e) {
- log.error("上传失败", e);
- return null;
- }
- return String.format("http://%s/%s/%s", domain, path, filename);
- }
- /**
- * 获取文件名的后缀
- *
- * @param file 表单文件
- * @param withPoint 是否带"。"
- * @return 后缀名
- */
- public static String getExtension(MultipartFile file, boolean withPoint) {
- if (null == file) {
- return "";
- }
- String fileName = StringUtils.isEmpty(file.getOriginalFilename()) ? file.getName() : file.getOriginalFilename();
- String extension = FileUtil.extName(fileName);
- if (StringUtils.isEmpty(extension) && StringUtils.isNotBlank(file.getContentType())) {
- extension = MimeTypeConstant.geByPrefix(file.getContentType());
- }
- extension = withPoint ? "." + extension : extension;
- return StringUtils.lowerCase(extension);
- }
- }
|