package com.gk.firework.Domain.Utils; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; public class UploadUtil { public static String uploadFile(MultipartFile file,String filePath) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String oldName = file.getOriginalFilename(); if (StringUtils.isBlank(oldName)) { return "null"; } String newName = sdf.format(new Date()) + oldName.substring(oldName.lastIndexOf(".")); File dest = new File(filePath, newName); String url = newName; if (!dest.getParentFile().exists()) { boolean rel = dest.getParentFile().mkdirs(); if (!rel) { throw new Exception("文件夹创建失败"); } } InputStream is = file.getInputStream(); OutputStream os = new FileOutputStream(dest); try { byte[] buffer = new byte[8 * 1024]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } } catch (Exception e) { throw e; } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } return url; } }