123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- 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<String,String> map = new HashMap<String,String>();
- private UploadFileUtils(){
- map.put("scmOrder","scmOrder");
- };
- /**
- * 获取路径
- * @param uploadType
- * @param soonPath
- * @return
- */
- public String getAllpath(String uploadType,String soonPath){
- String path = "";
- for (Map.Entry<String, String> 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;
- }
- }
|