package com.iamberry.rst.utils; import org.springframework.web.multipart.commons.CommonsMultipartFile; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; /** * 文件上传 */ public class UploadFileUtils { private static UploadFileUtils uploadFileUtils = new UploadFileUtils(); public static UploadFileUtils getUf(){ return uploadFileUtils; } private final Map map = new HashMap(); private UploadFileUtils(){ map.put("scmOrder","scmOrder"); }; /** * 获取路径 * @param uploadType * @param soonPath * @return */ public String getAllpath(String uploadType,String soonPath){ String path = ""; for (Map.Entry entry: map.entrySet()) { if(entry.getKey().equals(uploadType)){ path = "common/" +entry.getValue() + soonPath; } } if("".equals(path)){ if(soonPath ==null || "".equals(soonPath)){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); soonPath = sdf.format(new Date()); } path = "common/other/"+soonPath +"/"; } return path; } /** * 文件上传 * @param uploadType * @param rootPath * @param soonPath * @param name * @param file * @return */ public String upload(String uploadType, String rootPath, String soonPath, String name, CommonsMultipartFile file){ Integer flag = 0; String path = getAllpath(uploadType,soonPath); //common/scmOrder/upload/2019-02-21/ try { File targetFile = new File(rootPath + path); if (!targetFile.exists()) { targetFile.mkdirs(); } //获取输出流 OutputStream os=new FileOutputStream(rootPath+path+name); //获取输入流 CommonsMultipartFile 中可以直接得到文件的流 InputStream is = file.getInputStream(); byte[] bts = new byte[1024]; //一个一个字节的读取并写入 while(is.read(bts)!=-1) { os.write(bts); } os.flush(); os.close(); is.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return path+name; } /** * 上朵牙刷定制的图片上传 * @param name * @param file * @return */ public static String scmUploadFile(String rootPathh, String name, CommonsMultipartFile file){ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String soonPath = "/upload/"+ sdf.format(new Date()) + "/"; String path = UploadFileUtils.getUf().upload("scmOrder",rootPathh,soonPath,name,file); return path; } }