您好,登錄后才能下訂單哦!
在工作中要求將圖片上傳至本地,如下代碼將介紹如何將圖片上傳至本地
準備工作:
環境:eclipse4.5-x64,jdk1.7-x64,maven3
tomcat服務器配置圖片上傳映射:
上傳至本地服務器配置文件:image.properties
#\u672c\u5730\u670d\u52a1\u5668\u56fe\u7247\u4fdd\u5b58\u8def\u5f84 IMAGEPATH=/mall/upload/image/ #\u56fe\u7247\u540e\u7f00\u540d FILE_EXTEND_NAME=gif,jpg,jpeg,png,bmp #\u672c\u5730\u670d\u52a1\u5668\u89c6\u9891\u5b58\u50a8\u5730\u5740 MEDIAPATH=/mall/upload/media/ #\u89c6\u9891\u540e\u7f00\u540d MEDIA_EXTEND_NAME=mp4
controlle:UploadUtil.java
/** * 文件上傳工具類 * @author sang */ @Controller public class UploadUtil { /** 記錄日志對象 */ private static final MyLogger LOGGER = new MyLogger(UploadUtil.class); /**圖片格式錯誤信息*/ private static final String LOGGERINFO1 = "的圖片不符合限制"; /** * 備注: * uploadImgLocal,uploadImgOSS,ossConfMapper均是靜態成員變量 * 則添加注解注意只能用@Autowired且get,set方法不能有static否則報錯 * */ /**文件上傳:本地,注意*/ private static UploadImgLocal uploadImgLocal; /**文件上傳:OSS對象 */ private static UploadImgOSS uploadImgOSS; /**OSS配置查詢 */ private static OSSConfMapper ossConfMapper; public UploadImgLocal getUploadImgLocal() { return uploadImgLocal; } @Autowired public void setUploadImgLocal(UploadImgLocal uploadImgLocal) { UploadUtil.uploadImgLocal = uploadImgLocal; } public UploadImgOSS getUploadImgOSS() { return uploadImgOSS; } @Autowired public void setUploadImgOSS(UploadImgOSS uploadImgOSS) { UploadUtil.uploadImgOSS = uploadImgOSS; } public OSSConfMapper getOssConfMapper() { return ossConfMapper; } @Autowired public void setOssConfMapper(OSSConfMapper ossConfMapper) { UploadUtil.ossConfMapper = ossConfMapper; } /** * 上傳文件:去除85這個寬度 * @param muFile 上傳文件 * @param req * @return Map 返回中 key值{0,1,2,oldimg} 0小圖 1中圖 2大圖 oldimg原圖 */ public static synchronized Map<String, String> uploadFile(MultipartFile muFile,HttpServletRequest req) { Map<String, String> map = null; try { //查詢oss啟用狀態的配置信息 OSSConf ossConf=ossConfMapper.findByOssStatus(); if(muFile != null && muFile.getSize()>0 && ossConf!=null) { //檢查上傳的圖片的大小和擴展名 if (!UploadImgCommon.checkFileForSpringUpload(muFile)) { throw new RuntimeException("上傳" + muFile.getOriginalFilename() + LOGGERINFO1); } //oss類型0本地1阿里云2京東云 String ossType=ossConf.getOssType(); if("0".equals(ossType)){ //上傳本地 map = uploadImgLocal.uploadForABCSize(muFile); }else if("1".equals(ossType) || "2".equals(ossType)){ //上傳oss map=uploadImgOSS.uploadForABCSize(muFile,ossConf); } } } catch (Exception e) { e.printStackTrace(); LOGGER.error("上傳文件失敗"+e.getMessage(),e); } return map; } }
類:UploadImgLocal.java
/** * 上傳文件:本地 * @author somnus * */ @Component("uploadImgLocal") public class UploadImgLocal { /** 記錄日志對象 */ private static final MyLogger LOGGER = new MyLogger(UploadImgLocal.class); /**獲得當前項目訪問的地址 */ private static String url; @Resource(name = "SysHelperMapper") private SysHelperMapper sysHelperMapper; /** * 上傳文件:去除85這個寬度 * 存儲原圖地址如:http://127.0.0.1:8080:/mall/upload/image/20170804/1501811601145.jpg * @param muFile * @return Map 返回中 key值{0,1,2,oldimg} 0小圖 1中圖 2大圖 oldimg原圖 */ public Map<String, String> uploadForABCSize(MultipartFile muFile) { //封裝結果集 Map<String, String> imgMap = new HashMap<String, String>(); //服務器本地保存圖片路徑 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); //獲得當前項目訪問的地址:http://127.0.0.1:8080 url=UploadImgCommon.getHttpAndPort(request); //獲取上傳文件的保存路徑:文件拼接地址:服務器本地保存路徑+文件名+后綴 String fileNamess = UploadImgCommon.getPicNamePathSuffix(); try { File file = new File(fileNamess); //轉存文件到指定的路徑 muFile.transferTo(file); //獲取原圖地址 LOGGER.info(UploadImgCommon.LOGGERINFO1 + (url+fileNamess)); //存儲原圖地址如:/mall/upload/image/20170804/1501811601145.jpg imgMap.put(UploadImgCommon.OLDIMG, (url+fileNamess)); //圖片處理:獲取寬度集合,去除85這個寬度[352, 56, 160] int[] widths = UploadImgCommon.getImgSetOut85(sysHelperMapper.selectImageSet()); //給寬度集合升序排序 UploadImgCommon.sortWidth(widths);//[56,160,352] //縮放文件 File zoomFile=null; for(int i = 0; i < widths.length; i++){ //20171226新優化:將指定尺寸圖片存儲至本地 //縮放文件名 String zoomFileName=UploadImgCommon.picPath + UploadImgCommon.prefix + UploadImgCommon.SYMBOLS + widths[i] + UploadImgCommon.suffix; //創建縮放文件 zoomFile=new File(zoomFileName); //轉存文件到指定的路徑 muFile.transferTo(zoomFile); //獲取指定尺寸圖片地址:大圖352中160小56 LOGGER.info(widths[i]+UploadImgCommon.LOGGERINFO2+(url + UploadImgCommon.picPath + UploadImgCommon.prefix + UploadImgCommon.SYMBOLS + widths[i] + UploadImgCommon.suffix)); imgMap.put(i + "", (url + UploadImgCommon.picPath + UploadImgCommon.prefix + UploadImgCommon.SYMBOLS + widths[i] + UploadImgCommon.suffix)); } } catch (IllegalStateException e) { e.printStackTrace(); LOGGER.error(UploadImgCommon.LOGGERINFO3, e); } catch (IOException e) { e.printStackTrace(); LOGGER.error(UploadImgCommon.LOGGERINFO3, e); } catch (Exception e) { e.printStackTrace(); LOGGER.error(UploadImgCommon.LOGGERINFO3, e); } return imgMap; } }
公共方法:UploadImgCommon.java
package com.qianjiang.util.uploadutil; import java.io.File; import java.io.InputStream; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Properties; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.springframework.web.multipart.MultipartFile; import com.qianjiang.manager.bean.ImageSet; import com.qianjiang.util.MyLogger; import com.qianjiang.util.UtilDate; /** * 文件上傳公共方法 * @author somnus */ public class UploadImgCommon { /** 記錄日志對象 */ private static final MyLogger LOGGER = new MyLogger(UploadImgCommon.class); /**定義圖片*/ protected static final String IMAGE = "image"; /**定義視頻*/ protected static final String MEDIA="media"; /**定義圖片上傳最大限制10MB*/ private static long maxSize = 10 * 1024 * 1024; /**定義視頻上傳最大限制500MB */ private static long mediaMaxSize= 500 * 1024 * 1024; /**定義允許上傳文件擴展名 */ private static HashMap<String, String> extMap = new HashMap<String, String>(); /**文件保存路徑 */ protected static String picPath; /** 要保存的文件名 */ protected static String prefix; /**文件后綴 */ protected static String suffix; /**定位寬度集合循環次數*/ protected static final int THREE = 3; /**拼接圖片縮放特殊符號*/ protected static final String SYMBOLS="@"; /**圖片56縮放*/ protected static final int SMALL = 56; /**設置imgMap中返回小圖key值*/ protected static final int SMALLIMG=0; /**原圖*/ protected static final String OLDIMG = "oldimg"; protected static final String LOGGERINFO1 = "原圖地址:"; protected static final String LOGGERINFO2 = "尺寸的圖片地址:"; protected static final String LOGGERINFO3 = "圖片上傳,返回key值列表錯誤"; //本地上傳圖片properties屬性值 protected static final String IMAGEPATH = "IMAGEPATH"; //本地上傳視頻properties屬性值 protected static final String MEDIAPATH = "MEDIAPATH"; /**初始化*/ static { //允許圖片擴展名 extMap.put(IMAGE, "gif,jpg,jpeg,png,bmp"); //允許視頻擴展名 extMap.put(MEDIA, "mp4"); } /** * 獲取上傳文件的保存路徑 * 文件拼接地址:服務器本地保存路徑+文件名+后綴 * @return 文件名(全路徑) */ public static String getPicNamePathSuffix() { String fileName=""; try { //根據系統當前時間生成上傳后保存的文件名 long now = System.currentTimeMillis(); //文件名系統當前時間如1501848484869 prefix = String.valueOf(now); //文件路徑如:/mall/upload/image/20170804/ picPath = getHostAndPort().getProperty(IMAGEPATH) + UtilDate.todayFormatString(new Date()) + "/"; //根據真實路徑創建目錄文件 File picSaveFile = new File(picPath); if(!picSaveFile.exists()){ picSaveFile.mkdirs(); } //文件的后綴 suffix = ".jpg"; fileName=picPath + prefix + suffix; LOGGER.info("創建文件成功,文件名:"+fileName); } catch (Exception e) { e.printStackTrace(); LOGGER.error("創建本地文件失敗"+e.getMessage(),e); } return fileName; } /** * 上傳視頻存儲本地服務器 * 獲取上傳文件的保存名稱、服務器本地保存路徑、后綴,拼接成文件地址 * @return */ public static String getVideoNamePathSuffix() { String fileName=""; try { //根據系統當前時間生成上傳后保存的文件名 long now = System.currentTimeMillis(); //文件名系統當前時間如1501848484869 prefix = String.valueOf(now); //文件路徑如:/mall/upload/media/20170804/ picPath =getHostAndPort().getProperty(MEDIAPATH) + UtilDate.todayFormatString(new Date()) + "/"; //根據真實路徑創建目錄文件 File picSaveFile = new File(picPath); if(!picSaveFile.exists()){ picSaveFile.mkdirs(); } //文件的后綴(默認為MP4格式) UploadImgCommon.suffix = ".mp4"; fileName=picPath + prefix + suffix; LOGGER.info("創建視頻文件成功,文件名:"+fileName); } catch (Exception e) { e.printStackTrace(); LOGGER.error("創建上傳視頻本地服務器地址失敗:"+e.getLocalizedMessage(), e); } return fileName; } /** * 獲取寬度集合 * @return */ public static int[] getImgSet(List<ImageSet> imgSet) { int[] widths = new int[imgSet.size()]; for (int i = 0; i < imgSet.size(); i++) { widths[i] = Integer.parseInt(imgSet.get(i).getRuleWidth()); } return widths; } /** * 獲取寬度集合,去除85這個寬度 * @param imgSet * @return */ public static int[] getImgSetOut85(List<ImageSet> imgSet) { int[] widths = new int[THREE]; for (int i = 0; i < imgSet.size(); i++) { if ("85".equals(imgSet.get(i).getRuleWidth())) { if (i < 3) { i--; } continue; } widths[i] = Integer.parseInt(imgSet.get(i).getRuleWidth()); } return widths; } /** * 給寬度集合升序排序 * @param widths */ public static void sortWidth(int[] widths) { for (int i = 0; i < widths.length; i++) { for (int j = i + 1; j < widths.length; j++) { int temp; if (widths[i] > widths[j]) { temp = widths[i]; widths[i] = widths[j]; widths[j] = temp; } } } } /** * 獲得當前項目訪問的地址 * 比如http://127.0.0.1:8080 * @param request * @return 返回當前項目訪問的地址 */ public static String getHttpAndPort(HttpServletRequest request) { return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); } /** * 讀取配置文件信息 * @return */ public static Properties getHostAndPort() { Properties p = new Properties(); try{ InputStream inputStream = UploadImgCommon.class.getClassLoader().getResourceAsStream("config/image.properties"); p.load(inputStream); }catch(Exception e){ e.printStackTrace(); LOGGER.error("讀取Properties屬性文件錯誤"+e.getMessage(),e); } return p; } /** * SpringMVC上傳:驗證上傳圖片的大小和擴展名 * @param muFile 上傳文件 * @return 驗證通過返回true,否則返回false */ public static boolean checkFileForSpringUpload(MultipartFile muFile) { boolean bool = true; // 檢查文件大小 if (muFile.getSize() > maxSize) { LOGGER.error("=============>上傳" + muFile.getOriginalFilename() + "文件大小超過限制"); bool = false; return bool; } String fileName = muFile.getOriginalFilename(); //檢查擴展名 String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); if (!Arrays.<String> asList(extMap.get(IMAGE).split(",")).contains(fileExt)) { LOGGER.error("上傳文件" + muFile.getOriginalFilename() + "擴展名是不允許的擴展名。\n只允許" + extMap.get(IMAGE) + "格式。"); bool = false; return bool; } return bool; } /** * js引入Kindeditor插件實現文件上傳 * 驗證上傳文件大小和擴展名 * @param file 上傳文件 * @return 驗證通過返回true,否則返回false */ public static boolean checkFileAndMedia(FileItem file,String dirName) { boolean bool = true; //文件大小 long fileSize = file.getSize(); //文件名 String fileName = file.getName(); //檢查文件大小 if(fileSize > maxSize && fileSize > mediaMaxSize){ LOGGER.error("=============>上傳" + file.getFieldName() + "文件大小超過限制"); bool = false; return bool; } //檢查擴展名 String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){ LOGGER.error("上傳文件" + file.getFieldName() + "擴展名是不允許的擴展名。\n只允許" + extMap.get(dirName) + "格式。"); bool = false; return bool; } return bool; } }
上傳成功后控制臺打印信息:
上傳成功后前臺展示效果:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。