package com.hb.proj.utils; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.web.multipart.MultipartFile; import com.hb.proj.model.UploadResult; import com.hb.xframework.dao.util.UUIDHexGenerator; import jakarta.servlet.http.HttpServletRequest; public class UploadUtils { public static UploadResult saveFile(HttpServletRequest request,MultipartFile file,String subFolder,String accessPathPrefix) throws IllegalStateException, IOException { String OriginalFilename = file.getOriginalFilename();//获取原文件名 String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf(".")); String[] subPaths=subFolder.split("\\.|/"); String basePath=request.getSession().getServletContext().getRealPath(""); String relPath="upload"+File.separator+StringUtils.join(subPaths,File.separator); basePath=basePath+File.separator+relPath; FileUtils.forceMkdir(new File(basePath)); UUIDHexGenerator uuid=UUIDHexGenerator.getInstance(); String newFileName=uuid.generate()+suffixName; File localFile=new File(basePath+File.separator+newFileName); file.transferTo(localFile); String accessPath=accessPathPrefix+"/upload/"+StringUtils.join(subPaths,"/")+"/"+newFileName; return new UploadResult(newFileName,(relPath+File.separator+newFileName),accessPath); } public static void removeFile(HttpServletRequest request,String filePath){ try { String basePath=request.getSession().getServletContext().getRealPath(""); filePath=basePath+File.separator+filePath; File filedev=new File(filePath); if(filedev.exists()){ FileUtils.forceDelete(filedev); } } catch (IOException e) { e.printStackTrace(); } } }