package api.util.helper; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Objects; /** * @author Administrator */ @Component public class FileUploadHelper { /** * 根据文件路径上传 * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @return 文件名称 * @throws IOException */ public static String upload(String baseDir, MultipartFile file) throws IOException { try { int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length(); if (fileNamelength > 50) { throw new IOException("文件名不能超过50"); } long size = file.getSize(); if (size > 50 * 1024 * 1024) { throw new IOException("文件大小不能超过50mb"); } List exts= Arrays.asList( // 图片 "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" ); String fileName = file.getOriginalFilename(); String extension = fileName.substring(fileName.lastIndexOf(".") + 1); if (!exts.contains(extension)){ throw new IOException("此类文件不能上传"); } String newFileName = System.currentTimeMillis()+"."+extension; String filePath=baseDir + "/" + newFileName; File desc = new File(filePath); if (!desc.exists()) { if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } } String absPath = desc.getAbsolutePath(); file.transferTo(Paths.get(absPath)); return filePath; } catch (Exception e) { throw new IOException(e.getMessage(), e); } } /** * 根据文件路径上传 * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @return 文件名称 * @throws IOException */ public static String uploadImage(String baseDir, MultipartFile file) throws IOException { try { if (file.isEmpty()) { throw new IOException("无文件"); } int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length(); if (fileNamelength > 50) { throw new IOException("文件名不能超过50"); } long size = file.getSize(); if (size > 20 * 1024 * 1024) { throw new IOException("文件大小不能超过20mb"); } List exts = Arrays.asList("bmp", "gif", "jpg", "jpeg", "png"); String fileName = file.getOriginalFilename(); String extension = fileName.substring(fileName.lastIndexOf(".") + 1); if (!exts.contains(extension)) { throw new IOException("此类文件不能上传"); } String newFileName = System.currentTimeMillis() + "." + extension; String filePath = baseDir + "/" + newFileName; File desc = new File(filePath); if (!desc.exists()) { if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } } String absPath = desc.getAbsolutePath(); file.transferTo(Paths.get(absPath)); return filePath; } catch (Exception e) { throw new IOException(e.getMessage(), e); } } }