springmvc檔案上傳工具類
阿新 • • 發佈:2018-12-07
package com.wkrj.business.ntpd.until; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.util.FileCopyUtils; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; public class imgUploadUntil { public static List<Map<String, String>> lkh_uploadFile(HttpServletRequest request,String dirname){ ArrayList<Map<String, String>> newlist=new ArrayList<Map<String,String>>(); //檔案上傳 MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest) request; try { multipartRequest.setCharacterEncoding("UTF-8"); //檔案路徑 String path = dirname; String realPath = multipartRequest.getSession().getServletContext().getRealPath("/") + "/" + path; File file = new File(realPath); if (!file.exists()) {//建立目錄 file.mkdirs(); } String fileName = ""; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { String fileComponentName=entity.getKey();//獲取元件名 List<MultipartFile> list2 = multipartRequest.getFiles(fileComponentName); for (MultipartFile mf : list2) { fileName = mf.getOriginalFilename();// 獲取檔名 if(fileName==null||"".equals(fileName)||""==fileName){//空檔案,直接返回 return null; } String onlyfileName=fileName.substring(0,fileName.lastIndexOf("."));//只取名字,去掉副檔名 String extend = fileName.substring(fileName.lastIndexOf(".")+1);// 獲取副檔名 long noextfilename= System.currentTimeMillis();//獲取時間戳 這種速度更快一些 String extra = "wkrj";//由於樣式不能是數字所以加上wkrj來區分; String myfilename=extra+noextfilename+"."+extend;//自定義檔名稱 //檔案全路徑 String savePath = realPath + myfilename;// 檔案儲存全路徑 String fileurl=path+myfilename; File savefile = new File(savePath); // 檔案拷貝到指定硬碟目錄 FileCopyUtils.copy(mf.getBytes(), savefile); HashMap<String, String> map=new HashMap<String,String>(); map.put("fileextend", extend);//副檔名 map.put("fileurl", fileurl);//檔案相對路徑 map.put("filename", onlyfileName);//檔名 map.put("fileComponentName", fileComponentName);//前臺檔案元件的name值 newlist.add(map); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return newlist; } }