public class UploadImgUtils { private static String savePath = ""; /** * 上傳照片工具類 * * @param file 文件 * @param workNo 工單號 * @param property 配置的環境(dev,prod,test) * @return * @throws OperationException */ public static String uploadImg(MultipartFile file, String workNo, String property) throws OperationException { if (file == null) { System.out.println("異常"); } if (file.getSize() > 1024 * 1024 * 1) { System.out.println("異常"); } //獲取文件后綴 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1); if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) { System.out.println("異常"); } //對savePath進行過賦值 getProperties(property); File savePathFile = new File(savePath); if (!savePathFile.exists()) { //若不存在該目錄,則創建目錄 savePathFile.mkdir(); } //用工單號作為唯一的標識符 String filename = workNo + "." + suffix; try { //將文件保存指定目錄 file.transferTo(new File(savePath + filename)); } catch (Exception e) { System.out.println("異常"); } //返回文件名稱 return savePath + filename; } /** * 讀取配置文件中的信息. * * @return */ private static void getProperties(String name) { YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean(); factoryBean.setResources(new ClassPathResource("application-" + name + ".yml")); factoryBean.afterPropertiesSet(); Properties object = factoryBean.getObject();
在配置文件中書寫配置路徑信息 savePath = (String) object.get("savePath"); } }
上面的這個是工具類,需要在配置文件中配置上傳的路徑信息