赞
踩
file:
domain: http://172.11.1.1:9300(服务器ip:端口)
path: /home/admin/test(文件在linux的存放地址)
prefix: /statics
//资源映射路径 前缀
@Value("${file.prefix}")
public String localFilePrefix;
//域名或本机访问地址
@Value("${file.domain}")
public String domain;
//上传文件存储在本地的根路径
@Value("${file.path}")
private String localFilePath;
/** * 文件上传请求 */ @PostMapping("/upload") public R<List<SysFile>> upload(@RequestParam(name = "file", required = false) List<MultipartFile> files) { try { List<SysFile> list = new ArrayList<>(); for (MultipartFile file : files) { // 上传并返回访问地址 String url = sysFileService.uploadFile(file); String originalFilename = file.getOriginalFilename(); SysFile sysFile = new SysFile(); sysFile.setName(FileUtils.getName(url)); sysFile.setOriginalAttachmentName(originalFilename); sysFile.setUrl(url); sysFile.setDate(new Date()); list.add(sysFile); } return R.ok(list); } catch (Exception e) { log.error("上传文件失败", e); return R.fail(e.getMessage()); } }
/**
* 本地文件上传接口
*
* @param file 上传的文件
* @return 访问地址
* @throws Exception
*/
@Override
public String uploadFile(MultipartFile file) throws Exception
{
String name = FileUploadUtils.upload(localFilePath, file);
String url = domain + localFilePrefix + name;
return url;
}
package com.xinruan.file.utils; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.Objects; import org.apache.commons.io.FilenameUtils; import org.springframework.web.multipart.MultipartFile; import com.xinruan.common.core.exception.file.FileNameLengthLimitExceededException; import com.xinruan.common.core.exception.file.FileSizeLimitExceededException; import com.xinruan.common.core.exception.file.InvalidExtensionException; import com.xinruan.common.core.utils.DateUtils; import com.xinruan.common.core.utils.StringUtils; import com.xinruan.common.core.utils.file.MimeTypeUtils; import com.xinruan.common.core.utils.uuid.Seq; /** * 文件上传工具类 * * @author ruoyi */ public class FileUploadUtils { /** * 默认大小 50M */ public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024; /** * 默认的文件名最大长度 100 */ public static final int DEFAULT_FILE_NAME_LENGTH = 100; /** * 根据文件路径上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @return 文件名称 * @throws IOException */ public static final String upload(String baseDir, MultipartFile file) throws IOException { try { return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); } catch (Exception e) { throw new IOException(e.getMessage(), e); } } /** * 文件上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @param allowedExtension 上传文件类型 * @return 返回上传成功的文件名 * @throws FileSizeLimitExceededException 如果超出最大大小 * @throws FileNameLengthLimitExceededException 文件名太长 * @throws IOException 比如读写文件出错时 * @throws InvalidExtensionException 文件校验异常 */ public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, InvalidExtensionException { int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length(); if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) { throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH); } assertAllowed(file, allowedExtension);//文件大小校验和文件类型是否满足上传要求校验 String fileName = extractFilename(file); String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath(); file.transferTo(Paths.get(absPath)); return getPathFileName(fileName); } /** * 编码文件名 */ public static final String extractFilename(MultipartFile file) { // return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(), // FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), getExtension(file)); return StringUtils.format("{}/{}.{}", DateUtils.datePath(),Seq.getId(Seq.uploadSeqType), getExtension(file)); } private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException { File desc = new File(uploadDir + File.separator + fileName); if (!desc.exists()) { if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } } return desc.isAbsolute() ? desc : desc.getAbsoluteFile(); } private static final String getPathFileName(String fileName) throws IOException { String pathFileName = "/" + fileName; return pathFileName; } /** * 文件大小校验 * * @param file 上传的文件 * @throws FileSizeLimitExceededException 如果超出最大大小 * @throws InvalidExtensionException 文件校验异常 */ public static final void assertAllowed(MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, InvalidExtensionException { long size = file.getSize(); if (size > DEFAULT_MAX_SIZE) { throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024); } String fileName = file.getOriginalFilename(); String extension = getExtension(file);//获取文件名的后缀 if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))//判断上传的文件后缀是否满足要求 { if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) { throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension, fileName); } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) { throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension, fileName); } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) { throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension, fileName); } else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) { throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension, fileName); } else { throw new InvalidExtensionException(allowedExtension, extension, fileName); } } } /** * 判断MIME类型是否是允许的MIME类型 * * @param extension 上传文件类型 * @param allowedExtension 允许上传文件类型 * @return true/false */ public static final boolean isAllowedExtension(String extension, String[] allowedExtension) { for (String str : allowedExtension) { if (str.equalsIgnoreCase(extension)) { return true; } } return false; } /** * 获取文件名的后缀 * * @param file 表单文件 * @return 后缀名 */ public static final String getExtension(MultipartFile file) { String extension = FilenameUtils.getExtension(file.getOriginalFilename()); if (StringUtils.isEmpty(extension)) { extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType())); } return extension; } }
/**
* 日期路径 即年/月/日 如2018/08/08
*/
public static final String datePath()
{
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
package com.xinruan.common.core.utils.file; /** * 媒体类型工具类 * * @author ruoyi */ public class MimeTypeUtils { public static final String IMAGE_PNG = "image/png"; public static final String IMAGE_JPG = "image/jpg"; public static final String IMAGE_JPEG = "image/jpeg"; public static final String IMAGE_BMP = "image/bmp"; public static final String IMAGE_GIF = "image/gif"; public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" }; public static final String[] FLASH_EXTENSION = { "swf", "flv" }; public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", "asf", "rm", "rmvb" }; public static final String[] VIDEO_EXTENSION = { "mp4", "avi", "rmvb" }; public static final String[] DEFAULT_ALLOWED_EXTENSION = { // 图片 // "bmp", "gif", "jpg", "jpeg", "png", // // word excel powerpoint // "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt", // // 压缩文件 // "rar", "zip", "gz", "bz2", // // 视频格式 // "mp4", "avi", "rmvb", // // pdf // "pdf" "pdf", "bmp", "jpg", "JPEG", "png", "zip", "rar" }; public static String getExtension(String prefix) { switch (prefix) { case IMAGE_PNG: return "png"; case IMAGE_JPG: return "jpg"; case IMAGE_JPEG: return "jpeg"; case IMAGE_BMP: return "bmp"; case IMAGE_GIF: return "gif"; default: return ""; } } }
package com.xinruan.common.core.utils.uuid; import java.util.concurrent.atomic.AtomicInteger; import com.xinruan.common.core.utils.DateUtils; import com.xinruan.common.core.utils.StringUtils; /** * @author ruoyi 序列生成类 */ public class Seq { // 通用序列类型 public static final String commSeqType = "COMMON"; // 上传序列类型 public static final String uploadSeqType = "UPLOAD"; // 通用接口序列数 private static AtomicInteger commSeq = new AtomicInteger(1); // 上传接口序列数 private static AtomicInteger uploadSeq = new AtomicInteger(1); // 机器标识 private static String machineCode = "A"; /** * 获取通用序列号 * * @return 序列值 */ public static String getId() { return getId(commSeqType); } /** * 默认16位序列号 yyMMddHHmmss + 一位机器标识 + 3长度循环递增字符串 * * @return 序列值 */ public static String getId(String type) { AtomicInteger atomicInt = commSeq; if (uploadSeqType.equals(type)) { atomicInt = uploadSeq; } return getId(atomicInt, 3); } /** * 通用接口序列号 yyMMddHHmmss + 一位机器标识 + length长度循环递增字符串 * * @param atomicInt 序列数 * @param length 数值长度 * @return 序列值 */ public static String getId(AtomicInteger atomicInt, int length) { String result = DateUtils.dateTimeNow(); result += machineCode; result += getSeq(atomicInt, length); return result; } /** * 序列循环递增字符串[1, 10 的 (length)幂次方), 用0左补齐length位数 * * @return 序列值 */ private synchronized static String getSeq(AtomicInteger atomicInt, int length) { // 先取值再+1 int value = atomicInt.getAndIncrement(); // 如果更新后值>=10 的 (length)幂次方则重置为1 int maxSeq = (int) Math.pow(10, length); if (atomicInt.get() >= maxSeq) { atomicInt.set(1); } // 转字符串,用0左补齐 return StringUtils.padl(value, length); } }
转自若依官方代码
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。