UploadFileUtils.java 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package com.iamberry.rst.utils;
  2. import org.springframework.web.multipart.commons.CommonsMultipartFile;
  3. import java.io.*;
  4. import java.text.SimpleDateFormat;
  5. import java.util.*;
  6. /**
  7. * 文件上传
  8. */
  9. public class UploadFileUtils {
  10. private static UploadFileUtils uploadFileUtils = new UploadFileUtils();
  11. public static UploadFileUtils getUf(){
  12. return uploadFileUtils;
  13. }
  14. private final Map<String,String> map = new HashMap<String,String>();
  15. private UploadFileUtils(){
  16. map.put("scmOrder","scmOrder");
  17. };
  18. /**
  19. * 获取路径
  20. * @param uploadType
  21. * @param soonPath
  22. * @return
  23. */
  24. public String getAllpath(String uploadType,String soonPath){
  25. String path = "";
  26. for (Map.Entry<String, String> entry: map.entrySet()) {
  27. if(entry.getKey().equals(uploadType)){
  28. path = "common/" +entry.getValue() + soonPath;
  29. }
  30. }
  31. if("".equals(path)){
  32. if(soonPath ==null || "".equals(soonPath)){
  33. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  34. soonPath = sdf.format(new Date());
  35. }
  36. path = "common/other/"+soonPath +"/";
  37. }
  38. return path;
  39. }
  40. /**
  41. * 文件上传
  42. * @param uploadType
  43. * @param rootPath
  44. * @param soonPath
  45. * @param name
  46. * @param file
  47. * @return
  48. */
  49. public String upload(String uploadType, String rootPath, String soonPath, String name, CommonsMultipartFile file){
  50. Integer flag = 0;
  51. String path = getAllpath(uploadType,soonPath); //common/scmOrder/upload/2019-02-21/
  52. try {
  53. File targetFile = new File(rootPath + path);
  54. if (!targetFile.exists()) {
  55. targetFile.mkdirs();
  56. }
  57. //获取输出流
  58. OutputStream os=new FileOutputStream(rootPath+path+name);
  59. //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
  60. InputStream is = file.getInputStream();
  61. byte[] bts = new byte[1024];
  62. //一个一个字节的读取并写入
  63. while(is.read(bts)!=-1)
  64. {
  65. os.write(bts);
  66. }
  67. os.flush();
  68. os.close();
  69. is.close();
  70. } catch (FileNotFoundException e) {
  71. // TODO Auto-generated catch block
  72. e.printStackTrace();
  73. } catch (IOException e) {
  74. e.printStackTrace();
  75. }
  76. return path+name;
  77. }
  78. /**
  79. * 上朵牙刷定制的图片上传
  80. * @param name
  81. * @param file
  82. * @return
  83. */
  84. public static String scmUploadFile(String rootPathh, String name, CommonsMultipartFile file){
  85. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
  86. String soonPath = "/upload/"+ sdf.format(new Date()) + "/";
  87. String path = UploadFileUtils.getUf().upload("scmOrder",rootPathh,soonPath,name,file);
  88. return path;
  89. }
  90. }