fs.root=data/ #fs.root=/home/dev/fs/ #fs.root=D:/fs/ #fs.domains=182=http://172.16.100.182:18080,localhost=http://localhost:8080
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans default-lazy-init="false" default-autowire="no"> <!-- 圖片上傳配製 --> <bean id="fileUpload" class="com.xyt.gsm.utils.FileUpload"> <!-- 是否啓用temp文件文件夾 --> <property name="UploadTemp" value="false"/> <!-- 是否相對路徑 --> <property name="RELATIVE_SAVE" value="true"/> <!-- 限制大小 --> <property name="photoSize" value="2097152"/> <property name="otherSize" value="100000000"/> <!-- 文件真實存放文件夾 遠程server存放路徑 /gsm/fs/--> <!-- <property name="realFilePath" value="smb://gsm:gsm1234@172.16.100.182/home/"/> --> <!-- 文件真實存放文件夾 本地server存入--> <property name="realFilePath" value="${fs.root}"/> <!-- 文件暫時文件夾 --> <!-- <property name="UPLOADDIR" value="fs/temp/"/> --> </bean> <bean id="fileUploadServiceImp" class="com.xyt.gsm.service.fs.imp.FileUploadServiceImp"> <property name="productPhotoService" ref="productPhotoServiceImp"></property> <property name="dictService" ref="dictService"></property> </bean> <!-- 絕對路徑要在tomcat 作下面映射 --> <!-- <Context path="/fs" docBase="d:/fs" /> --> </beans>
package com.xyt.gsm.utils; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.UUID; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import jcifs.smb.SmbException; import jcifs.smb.SmbFile; import jcifs.smb.SmbFileOutputStream; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import com.xyt.gsm.constant.Fs; import com.xyt.gsm.constant.Fs.UpoladStatus; /** * 圖片上傳 * * @author liangrui * * UploadTemp 假設爲false 暫時所在文件夾被實際文件夾替換,假設爲true 需要再作一次拷貝 * */ public class FileUpload { // 文件信息 /** 是否啓用暫時文件文件夾 */ private static boolean UploadTemp = false; /** 文件上傳相對 路徑 */ private static String RELATIVEPATH = "relativePath"; /** 文件上傳絕對 路徑文件夾 */ private static String ABSOLUTEPATH = "absolutePath"; /** 實際文件所在文件夾 */ private static String realFilePath = "fs/"; /** 文件上傳暫時所在文件夾 */ public static String UPLOADDIR = "fs/temp/"; /** 圖片上傳限制大小 */ public static Integer photoSize = 2097152;// /** 末知類型文件上限制大小 */ private static Integer otherSize = 100000000; /** 是否存放相對路徑 **/ private static boolean RELATIVE_SAVE = false; // fied public void setUploadTemp(boolean uploadTemp) { UploadTemp = uploadTemp; } public void setPhotoSize(Integer photoSize) { FileUpload.photoSize = photoSize; } public void setOtherSize(Integer otherSize) { FileUpload.otherSize = otherSize; } public void setRealFilePath(String realFilePath) { if (UploadTemp == false) UPLOADDIR = realFilePath; FileUpload.realFilePath = realFilePath; } public void setUPLOADDIR(String uPLOADDIR) { if (UploadTemp == false) UPLOADDIR = realFilePath; else UPLOADDIR = uPLOADDIR; } public static void setRELATIVE_SAVE(boolean rELATIVE_SAVE) { RELATIVE_SAVE = rELATIVE_SAVE; } public static String getRealFilePath() { return realFilePath; } /** * * @param request * 上傳文件的請求 * @param suffuxDir * 文件夾分配 * @param type * 上傳文件的類型 * @param cutPhoto * 是否切圖 * @return 上傳後的文件路徑 * @throws IllegalStateException * @throws IOException */ // =============================================================================================== // -----解析request 上傳 返回上傳後的文件把在路徑 // ================================================================================================ public static List<String> fileUpload(HttpServletRequest request, String suffuxDir, String type) throws IllegalStateException, IOException { return fileUpload(request, suffuxDir, type, false); } public static List<String> fileUpload(HttpServletRequest request, String suffuxDir, String type, Boolean cutPhoto) throws IllegalStateException, IOException { // 上傳文件的解析器 CommonsMultipartResolver mutiparRe = new CommonsMultipartResolver(); if (mutiparRe.isMultipart(request)) {// 假設是文件類型的請求 List<String> fileInfo = new ArrayList<String>(); MultipartHttpServletRequest mhr = (MultipartHttpServletRequest) request; // 按月分文件夾 DateFormat df = new SimpleDateFormat("yyyyMM"); String month = df.format(new Date()); // 獲取路徑 String uploadDir = ""; if (RELATIVE_SAVE) { uploadDir += (request.getSession().getServletContext().getRealPath("/")+FileUpload.realFilePath); }else { uploadDir += FileUpload.UPLOADDIR ; } uploadDir+=(suffuxDir + month + "/"); // 假設文件夾不存在,建立一個文件夾 if (!new File(uploadDir).exists()) { File dir = new File(uploadDir); dir.mkdirs(); } // 跌帶文件名稱稱 Iterator<String> it = mhr.getFileNames(); while (it.hasNext()) { final MultipartFile mf = mhr.getFile(it.next()); // 獲取一個文件 if (mf != null) { // 假設是圖片類型文件上傳 限制大小和類型 if (type.equals(Fs.FileUpLoadType.PHOTO)) { if (!checkingPhoto(mf)) { fileInfo.add(UpoladStatus.類型無效或圖片過大.toString()); continue; } } else { if (mf.getSize() > otherSize) { fileInfo.add(UpoladStatus.類型無效或圖片過大.toString()); continue; } } // 其餘上傳類型 另外作限制推斷 String resFileName = mf.getOriginalFilename();// 獲取原文件名稱 // 取得文件名稱和後輟 String suffix = ""; if (resFileName.indexOf(".") != -1) { suffix = resFileName.substring(resFileName.lastIndexOf(".") + 1); } String dian = "."; if ("".equals(suffix)) dian = ""; // 保存的文件名稱 String uuid = rename(); String fileName = uuid + dian + suffix; File outFile = new File(uploadDir + fileName); // 路徑加文件名稱 +"/" mf.transferTo(outFile); // 保存到 if (cutPhoto) { final String dirAndUuid = uploadDir + uuid; final String dians = dian; final String suffixs = suffix; new Thread(new Runnable() { public void run() { try { copyImgSpecification(mf.getInputStream(), dirAndUuid, dians, suffixs); } catch (IOException e) { e.printStackTrace(); } } }).start(); } if (RELATIVE_SAVE) {// 相對路徑文件夾 fileInfo.add("/" + FileUpload.realFilePath + suffuxDir + month + "/" + fileName);// 文件路徑 } else {// 絕對路徑文件夾 fileInfo.add("/" + suffuxDir + month + "/" + fileName);// 文件路徑 } } } return fileInfo; } return null; } // ------------------------------------------------------------------------------------------------------------ // 複製圖片 改變不一樣大小的規格 // ------------------------------------------------------------------------------------------------------------ public static void copyImgSpecification(InputStream is, String DirAnduuid, String dian, String suffix) throws IOException { Image img = ImageIO.read(is); FileOutputStream fos = null; for (int i = 0; i < Fs.FileUpLoadType.changePhotoSize.length; i++) { int w = Fs.FileUpLoadType.changePhotoSize[i]; // int h=imgSize[i]; String allPath = DirAnduuid + "_" + w + "x" + w + dian + suffix; if ("".equals(suffix)) { suffix = "jpg"; } fos = new FileOutputStream(allPath); // 輸出到文件流 chagePhotoSize(allPath, img, fos, suffix, w, w); } img.flush(); // if(fos!=null){fos.close();} } // ---------------------------------------------------------------- // 檢查圖片類型上傳和圖片大小 // ---------------------------------------------------------------- public static boolean checkingPhoto(MultipartFile mf) throws IOException { if (!isImage(mf.getInputStream())) { // 推斷是否爲圖片 // fileInfo.add("請上傳有效圖片文件");//提示信息 return false; } if (mf.getSize() > photoSize) { // fileInfo.add("圖片大於"+(new // DecimalFormat("####.##").format(((double)photoSize)/1024/1024))+"MB上傳失敗");//提示信息 return false; } return true; } // 僅僅生成uuid 和後輟分開。切圖時需要 public static String rename(/* String name */) { // 時分秒 /* * Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss") .format(new Date())); * Long random = (long) (Math.random() * now); String fileName = now + "" + random; */ // 不能設置種子值,應採用默認的方式(系統時間戳 ) final Random rd = new Random(); final Long random = rd.nextLong(); String num = String.valueOf(random); // 限制5個字符 int limit = 5; if (num.length() > limit) { num = num.substring(0, limit); } // uuid生成文件名稱 UUID uuid = UUID.randomUUID(); // 加上 5位隨機數 String uustr = uuid.toString().replace("-", "") + num; /* * if (name.indexOf(".") != -1) { uustr += name.substring(name.lastIndexOf(".")); } else { * return uustr; } */ return uustr; } // 更改文件名稱稱 public static String rename(String name) { // 時分秒 /* * Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss") .format(new Date())); * Long random = (long) (Math.random() * now); String fileName = now + "" + random; */ // 不能設置種子值,應採用默認的方式(系統時間戳 ) final Random rd = new Random(); final Long random = rd.nextLong(); String num = String.valueOf(random); // 限制5個字符 int limit = 5; if (num.length() > limit) { num = num.substring(0, limit); } // uuid生成文件名稱 UUID uuid = UUID.randomUUID(); // 加上 5位隨機數 String uustr = uuid.toString().replace("-", "") + num; if (name.indexOf(".") != -1) { uustr += name.substring(name.lastIndexOf(".")); } else { return uustr; } return uustr; } // =============================================================================================== // -----推斷是否爲圖片 // ================================================================================================ public static boolean isImage(File imageFile) { if (!imageFile.exists()) { return false; } Image img = null; try { img = ImageIO.read(imageFile); if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) { return false; } return true; } catch (Exception e) { return false; } finally { img = null; } } public static boolean isImage(InputStream imageFile) { Image img = null; try { img = ImageIO.read(imageFile); if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) { return false; } return true; } catch (Exception e) { return false; } finally { img = null; } } // =============================================================================================== // -----刪除 // ================================================================================================ public static int deleteFile(HttpServletRequest request, boolean cutPhoto, String... path) throws MalformedURLException, SmbException { // List<String> delList=new ArrayList<String>();//記錄成功刪除的文件名稱 int delcount = 0; // 遠程刪除 if (realFilePath.length() > 3 && realFilePath.substring(0, 3).equals("smb")) { for (String pa : path) { SmbFile remoteFile = new SmbFile(pa); if (remoteFile.exists()) { remoteFile.delete(); delcount++; // 獲取文件名稱 // delList.add(p.substring(p.lastIndexOf("/")+1)); } } } else { // 獲取當前根文件夾 本地刪除 String proPath = ""; if (RELATIVE_SAVE) { proPath += request.getSession().getServletContext().getRealPath("/"); } else { proPath += FileUpload.UPLOADDIR; } for (String p : path) { File file = new File(proPath + p); if (file.exists()) { file.delete(); delcount++; // 獲取文件名稱 // delList.add(p.substring(p.lastIndexOf("/")+1)); // 刪除小圖 if (cutPhoto) { Integer[] xPhotoArr = Fs.FileUpLoadType.changePhotoSize; for (Integer imgSize : xPhotoArr) { String suffixs =""; String prefix=p; if(p.indexOf(".")!=-1){ suffixs = p.substring(p.lastIndexOf(".")); prefix = p.substring(0, p.lastIndexOf(".")); } String newP = prefix + "_" + imgSize + "x" + imgSize + suffixs; File filex = new File(proPath + newP); if (filex.exists()) { filex.delete(); delcount++; } } } } } } return delcount; } /** * * @param request * @param path * 暫時圖片文件夾 * @param prefixDir * 前輟文件夾 比方 "商品ID文件夾,商品圖片文件夾" * @return * @throws IOException */ // ------------------------------------------------------------------------------------------- // 把temp的圖片文件複製到 真實存放文件文件夾/日期文件夾中 // ----------------------------------------------------------------------------------------------- public static String tempToupdateImgPath(HttpServletRequest request, String path, String... prefixDir) throws IOException { // 主文件夾 String rootDir = request.getSession().getServletContext().getRealPath("/"); File file = new File(rootDir + path);// 需要移動的圖片 String realPath = "";// 實際圖片地址 String dbPath = "";// 保存數據庫 String fileName = path.substring(path.lastIndexOf("/") + 1);// 文件名稱 // 加上前輟文件夾 StringBuffer appendDir = new StringBuffer(); for (String zdir : prefixDir) { appendDir.append(zdir + "/"); } // smb://username:password@192.168.0.77 // 假設是smb遠程 上傳遠程server if (realFilePath.length() > 3 && realFilePath.substring(0, 3).equals("smb")) { dbPath = fileToRemoto(file, fileName, appendDir.toString()); } else { // 上傳到本地server dbPath = realFilePath + appendDir.toString() + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/"; realPath = rootDir + dbPath; if (!new File(realPath).exists()) { File dir = new File(realPath); dir.mkdirs(); } file.renameTo(new File(realPath + fileName)); } return "/" + dbPath + fileName; } // ------------------------------------------------------------------------------------------- // 通用smb 傳送文件到遠程 配製路徑 前三個字符爲 smb開頭 // ----------------------------------------------------------------------------------------------- private static String fileToRemoto(File file, String fileName, String prefixDir) { InputStream in = null; OutputStream out = null; String returnPath = null; try { // 獲取流 in = new BufferedInputStream(new FileInputStream(file)); String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/"; SmbFile remoteFile = new SmbFile(realFilePath + dateDir); // ip+... String fixed = realFilePath.substring(realFilePath.indexOf('@') + 1); returnPath = fixed + prefixDir + dateDir + fileName; if (!remoteFile.exists()) { remoteFile.mkdirs(); } // 將遠程的文件路徑傳入SmbFileOutputStream中 並用 緩衝流套接 String inputFilePath = remoteFile + "/" + fileName; // System.out.println("remoteFile: "+remoteFile); out = new BufferedOutputStream(new SmbFileOutputStream(inputFilePath)); byte[] buffer = new byte[1024]; while (in.read(buffer) != -1) { out.write(buffer); buffer = new byte[1024]; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return returnPath; } // ---------------------------------------------------------------------------------------- // 改變圖片大小 // -------------------------------------------------------------------------------------- private static void chagePhotoSize(final String path, Image src/* FileInputStream is */, FileOutputStream fos, final String format, int w, int h) throws IOException { try { int old_w = src.getWidth(null); // 獲得源圖寬 int old_h = src.getHeight(null); int new_w = 0; int new_h = 0; // 獲得源圖長 double w2 = (old_w * 1.00) / (w * 1.00); double h2 = (old_h * 1.00) / (h * 1.00); /** * BufferedImage(,,) width - 所建立圖像的寬度 height - 所建立圖像的高度 imageType - 所建立圖像的類型 */ // 圖片跟據長寬留白。成一個正方形圖。BufferedImage oldpic; if (old_w > old_h) { // BufferedImage.TYPE_INT_RGB; //0-13 oldpic = new BufferedImage(old_w, old_w, 1); } else { if (old_w < old_h) { oldpic = new BufferedImage(old_h, old_h, 1); } else { oldpic = new BufferedImage(old_w, old_h, 1); } } // 改變圖片大小 Graphics2D g = oldpic.createGraphics(); g.setColor(Color.white); if (old_w > old_h) { /** * x - 要填充矩形的 x 座標。javascript
y - 要填充矩形的 y 座標。 width - 要填充矩形的寬度。 height - 要填充矩形的高度。 */ g.fillRect(0, 0, old_w, old_w); /** * img - 要繪製的指定圖像。html
假設 img 爲 null,則此方法不運行不論什麼操做。 x - x 座標。前端
y - y 座標。java
width - 矩形的寬度。 * height - 矩形的高度。web
bgcolor - 在圖像非透明部分下繪製的背景色。 observer - 當轉換了不少其餘圖像時要通知的對象。 */ g.drawImage(src, 0, (old_w - old_h) / 2, old_w, old_h, Color.white, null); } else { if (old_w < old_h) { g.fillRect(0, 0, old_h, old_h); g.drawImage(src, (old_h - old_w) / 2, 0, old_w, old_h, Color.white, null); } else { // g.fillRect(0,0,old_h,old_h); /** * getScaledInstance() width - 將圖像縮放到的寬度。算法
height - 將圖像縮放到的高度。spring
hints - * 指示用於圖像又一次取樣的算法類型的標誌。數據庫
*/ g.drawImage(src.getScaledInstance(old_w, old_h, Image.SCALE_SMOOTH), 0, 0, null); } } g.dispose(); src = oldpic; // 原寬大於指定寬 if (old_w > w) new_w = (int) Math.round(old_w / w2); else new_w = old_w; // 原高大於指定高 if (old_h > h) new_h = (int) Math.round(old_h / h2); else new_h = old_h; BufferedImage tag = new BufferedImage(new_w, new_h, 4); tag.getGraphics().drawImage(src.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0, 0, null); ImageIO.write(tag, format, fos); tag.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { if (fos != null) { fos.close(); } } } // ==========在服務端爲用戶保存圖片上傳信息================================================ // private static final ThreadLocal<> threadLocal =new ThreadLocal<>(); } apache
package com.xyt.gsm.service.fs; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.xyt.gsm.bean.common.ResultBean; import com.xyt.gsm.entity.mgr.User; public interface FileUploadService { String singleUpload(HttpServletRequest request, User user, String suffixDir, String type, Boolean cutPhoto) throws Exception;// List<?> MonyUpload(HttpServletRequest request, User user, String suffixDir);// int deleteFile(HttpServletRequest request, boolean cutPhoto, String... path); ResultBean deleteFileAnDb(HttpServletRequest request, String type, String id, boolean cutPhoto, String... path) throws Exception; String singleUpload(HttpServletRequest request, User user, String suffixDir, String type, Boolean cutPhoto, String merchantId) throws Exception;// List<String> singleUpload(HttpServletRequest request, String suffixDir, String type, Boolean cutPhoto, String merchantId) throws Exception;// void download(); }
package com.xyt.gsm.service.fs.imp; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.xyt.gsm.bean.common.ResultBean; import com.xyt.gsm.constant.CommonConstants; import com.xyt.gsm.constant.DictConstants; import com.xyt.gsm.constant.Fs; import com.xyt.gsm.constant.Fs.UpoladStatus; import com.xyt.gsm.entity.mgr.User; import com.xyt.gsm.service.fs.FileUploadService; import com.xyt.gsm.service.mgr.DictService; import com.xyt.gsm.service.mgr.ProductPhotoService; import com.xyt.gsm.utils.FileUpload; public class FileUploadServiceImp implements FileUploadService { protected Log log = LogFactory.getLog(this.getClass().getName()); private ProductPhotoService productPhotoService; private DictService dictService; public void setProductPhotoService(ProductPhotoService productPhotoService) { this.productPhotoService = productPhotoService; } public void setDictService(DictService dictService) { this.dictService = dictService; } @Override public String singleUpload(HttpServletRequest request, User user, String suffixDir, String type, Boolean cutPhoto, String merchantId) throws Exception { String path = ""; // 圖片上傳類型 if (type.equals(Fs.FileUpLoadType.PHOTO)) { if (user == null) return UpoladStatus.上傳失敗末知錯誤.toString(); if ("".equals(merchantId) || merchantId == null) { // 運營人員操做 爲 還有一文件夾下 if (CommonConstants.RoleType.OPERATER.equals(user.getUserType())) { //merchantId = Fs.FileDir.OPERATION_DIR; merchantId = ""; } else { //獲取供應商id merchantId = user.getMerchantId(); } } // 推斷數據字典裏是否有該文件夾 Map<String, String> photos = (Map<String, String>) dictService.getDictMap(DictConstants.ClsCode.FS); if (!matchDir(photos, suffixDir)) { // suffixDir=FileDir.NOT_DIR; path=com.xyt.gsm.constant.Fs.UpoladStatus.文件文件夾未分配.name(); } else { // 商家id /處理 merchantId = manageSeparator(merchantId); // suffixdri suffixDir = manageSeparator(suffixDir); path = FileUpload.fileUpload(request, merchantId + suffixDir, Fs.FileUpLoadType.PHOTO, cutPhoto).get(0); } } return path; } @Override public String singleUpload(HttpServletRequest request, User user, String suffixDir, String type, Boolean cutPhoto) throws Exception { return singleUpload(request, user, suffixDir, type, cutPhoto, ""); } @Override public List<?> MonyUpload(HttpServletRequest request, User user, String suffixDir) { // TODO Auto-generated method stub return null; } @Override public int deleteFile(HttpServletRequest request, boolean cutPhoto, String... path) { return 0; } @Override public void download() { // TODO Auto-generated method stub } // 處理 / 先後有無/都可以 public String manageSeparator(String str) { if (str == null) str = ""; if (!"".equals(str)) {// --05/01/ // 不需要/ if (str.startsWith("/")) str = str.substring(1); // 要加上/ if (!str.endsWith("/")) str = str + "/"; } return str; } // ------------------------------------------- // 匹配前端的文件夾和數據庫的文件夾是否一至,以防先後有無/問題 // ------------------------------------------- public boolean matchDir(Map<String, String> photos, String webDir) { if (photos == null) return false; if (webDir == null) webDir = ""; boolean isMatch = false; if (photos.containsKey(webDir)) return true; String temp = ""; // 不匹配的狀況下!再進行先後/處理匹配 if (webDir.startsWith("/")) { // 前面 不要/ temp = webDir.substring(1); if (photos.containsKey(temp)) return true; } if (webDir.endsWith("/")) { // 後面 不要/ temp = webDir.substring(0, webDir.length() - 1); if (photos.containsKey(temp)) return true; } if (!webDir.endsWith("/")) { // 後面 要/ temp = webDir + "/"; if (photos.containsKey(temp)) return true; } if (!webDir.startsWith("/")) { // 前面 要/ temp = "/" + webDir; if (photos.containsKey(temp)) return true; } // 前面 後面要/ if (!webDir.startsWith("/") && !webDir.endsWith("/")) { temp = "/" + webDir + "/"; if (photos.containsKey(temp)) return true; } // 前面 後面 不要/ if (webDir.startsWith("/") && webDir.endsWith("/")) { temp = webDir.substring(1, webDir.length() - 1); if (photos.containsKey(temp)) return true; } return isMatch; } @Override public ResultBean deleteFileAnDb(HttpServletRequest request, String type, String id, boolean cutPhoto, String... path) throws Exception { ResultBean rb = new ResultBean(); if (type.equals(Fs.FileUpLoadType.PHOTO)) { // 刪除數據 int count = productPhotoService.deleteByProductId(id); if (count > 0) { // 刪除圖片 int cou = FileUpload.deleteFile(request, cutPhoto, path); if (0 >= cou) { log.warn("id:" + id + ": 數據刪除成功!圖片刪除失敗"); } } else { rb.setSuccess(false); } } return rb; } @Override public List<String> singleUpload(HttpServletRequest request, String suffixDir, String type, Boolean cutPhoto, String merchantId) throws Exception { List<String> paths = null; // 圖片上傳類型 if (type.equals(Fs.FileUpLoadType.PHOTO)) { // 推斷數據字典裏是否有該文件夾 Map<String, String> photos = (Map<String, String>) dictService.getDictMap(DictConstants.ClsCode.FS); if (!matchDir(photos, suffixDir)) { // suffixDir=FileDir.NOT_DIR; // path=com.xyt.gsm.constant.Fs.UpoladStatus.文件文件夾未分配.name(); } else { // 商家id /處理 merchantId = manageSeparator(merchantId); // suffixdri suffixDir = manageSeparator(suffixDir); paths = FileUpload.fileUpload(request, merchantId + suffixDir, Fs.FileUpLoadType.PHOTO, cutPhoto); } } return paths; } }
package com.xyt.gsm.mvc.controller.fs; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.JsonObject; import com.xyt.gsm.bean.common.ResultBean; import com.xyt.gsm.bean.mgr.FileUploadVo; import com.xyt.gsm.bean.mgr.LoginUser; import com.xyt.gsm.constant.CommonConstants; import com.xyt.gsm.constant.Fs; import com.xyt.gsm.constant.Fs.UpoladStatus; import com.xyt.gsm.entity.mgr.ProductPhoto; import com.xyt.gsm.entity.mgr.User; import com.xyt.gsm.mvc.controller.BaseController; import com.xyt.gsm.service.fs.FileUploadService; import com.xyt.gsm.service.ice.MerchantService; import com.xyt.gsm.utils.FileUpload; import com.xyt.gsm.utils.StringUtil; /** * 圖片上傳接口 controller * * @author liangrui * */ @Controller @RequestMapping(CommonConstants.UriPrefix.PC + CommonConstants.Menu.SYS + "/photoupload") public class PhotoUploadController extends BaseController { protected Log log = LogFactory.getLog(this.getClass().getName()); @Resource FileUploadService fileUploadService; @Resource MerchantService merchantService; // 多張上傳 @ResponseBody @RequestMapping(value = "/manyup") public List<String> ManyUp(HttpServletRequest request, HttpServletResponse response, String suffixDir) throws IllegalStateException, IOException { List<String> fileInfo = null; return fileInfo; } // ----------------------------------------------------------------------------------- // 單張圖片上傳,返回路徑 //@currentDomain:解決跨域。傳值爲==》主域server下的子頁面 在子頁面 週轉, 回調父頁面的JS函數 // ---------------------------------------------------------------------------------- @RequestMapping(value = "/singleup", method = RequestMethod.POST) public void SingleUp(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "suffixDir", required = true) String suffixDir, @RequestParam(required = false, value = "cutPhoto") boolean cutPhoto, @RequestParam(required = false, value = "merchantId") String merchantId) throws Exception { StringBuffer basePath=new StringBuffer(request.getScheme()); basePath.append("://"); basePath.append(request.getServerName()); basePath.append(":"); basePath.append(request.getServerPort()); basePath.append(request.getContextPath()); basePath.append("/"); //basePath.append(FileUpload.getRealFilePath()/*.substring(0,FileUpload.getRealFilePath().length()-1)*/); User user = super.getLoginUser(request).getUser(); if (user != null) { String filePath = fileUploadService.singleUpload(request, user, suffixDir, Fs.FileUpLoadType.PHOTO, cutPhoto, merchantId); // 處理返回狀態 UpoladStatus result = getStatus(filePath); String PromptSize = ""; if (UpoladStatus.類型無效或圖片過大.toString().equals(result.toString())) { // 2^10=1024 PromptSize = "(最大限制:" + (FileUpload.photoSize >> 20) + "MB)"; } PrintWriter out = response.getWriter(); response.setHeader("Cache-Control", "none-cache"); String idnum = request.getParameter("idnum"); String reutrnDate = "{'id':'" + idnum + "','filePath':'" + basePath.append(filePath).toString() + "','dbFilePath':'" + filePath + "','status':{'code':'" + result.ordinal() + "','message':'" + result.name() + PromptSize + "'}}"; String currentDomain = request.getParameter("currentDomain"); //<script>parent.parent.callback(" + reutrnDate + ");</script> String ret="<iframe id=\"ifr\" src=\""+currentDomain+"#"+reutrnDate+"\"></iframe>"; out.print(ret); } } @RequestMapping(value = "/saveImage", method = RequestMethod.POST) public void saveImage(HttpServletRequest request, HttpServletResponse response, FileUploadVo vo) throws Exception { // 刪除舊的沒用的圖片 if (!StringUtil.isEmpty(vo.getOldImagePath()) && vo.getOldImagePath().startsWith("/")) { FileUpload.deleteFile(request, vo.getCutPhoto(), vo.getOldImagePath()); } User user = super.getLoginUser(request).getUser(); String filePath = fileUploadService.singleUpload(request, user, vo.getSuffixDir(), Fs.FileUpLoadType.PHOTO, vo.getCutPhoto(), vo.getMerchantId()); JsonObject json = new JsonObject(); json.addProperty("filePath", filePath); json.addProperty("success", false); if (!StringUtil.isEmpty(filePath) && filePath.startsWith("/")) { json.addProperty("success", true); } String result="<iframe id=\"ifr01001\" src='"+vo.getCallbackPath()+"#"+json.toString()+"'></iframe>"; responseText(response, result); } /** * 響應請求 * * @param response * @param result * @throws IOException */ private void responseText(HttpServletResponse response, String result) throws IOException { response.setHeader("pragma", "no-cache"); response.setHeader("cache-control", "no-no-cache"); response.setHeader("expires", "0"); response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = null; try { out = response.getWriter(); out.print(result); out.flush(); } finally { if (out != null) { out.close(); } } } // ----------------------------------------------------------------------------------- // 商品 圖片數據和存儲圖片 刪除 依據id // ---------------------------------------------------------------------------------- @ResponseBody @RequestMapping(value = "/delimgandb") public ResultBean delImgAnDB(HttpServletRequest request, HttpServletResponse response, ProductPhoto photo, @RequestParam(required = true, value = "id") String id, @RequestParam(value = "cutPhoto", required = false) boolean cutPhoto, @RequestParam(value = "path") String path) throws Exception { return fileUploadService.deleteFileAnDb(request, Fs.FileUpLoadType.PHOTO, id, cutPhoto, path); } // ----------------------------------------------------------------------------------- // 僅僅 刪除存儲圖片 // ---------------------------------------------------------------------------------- // @ResponseBody @RequestMapping(value = "/delimg") public void delImg(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "path", required = true) String[] path, @RequestParam(value = "cutPhoto", required = false) boolean cutPhoto) throws Exception { if (path.length > 0) { FileUpload.deleteFile(request, cutPhoto, path); } } // 得到圖片返回狀態 public UpoladStatus getStatus(String filePath) { UpoladStatus result = UpoladStatus.上傳失敗末知錯誤; boolean isUp = true; for (UpoladStatus u : UpoladStatus.values()) { if (filePath.equals(u.toString())) { result = u; isUp = false; break; } } if (isUp) { result = UpoladStatus.SEUCCESS; } return result; } // ----------------------------------------------------------------------------------- // 獲取上傳server的域名 // 依據用戶類型獲取, // 假設是商家。code 爲null 默認取商家商品域名, 傳參數 "1" 取商家域名 // ---------------------------------------------------------------------------------- @RequestMapping(value = "/getdomain", method = RequestMethod.POST) @ResponseBody public String getUpPhotoDomain(HttpServletRequest request, HttpServletResponse response, String code) { String domain = ""; LoginUser user = super.getLoginUser(request); if (user != null) { // 運營 if (CommonConstants.RoleType.OPERATER.equals(user.getUser().getUserType())) { domain = user.getPublicUploadDomain(); } else if (CommonConstants.RoleType.MERCHANT.equals(user.getUser().getUserType())) { if (null == code || "".equals(code)) { domain = user.getMerchantProductDomain(); // 假設沒有取到 if (null == domain || "".equals(domain)) { { // 獲取域名 domain = merchantService.getMerchantDomain(user.getUser().getMerchantId()).getProductDomain(); } } else if ("1".equals(code)) { domain = user.getMerchantDomain(); // 假設沒有取到 if (null == domain || "".equals(domain)) { { // 獲取域名 domain = merchantService.getMerchantDomain(user.getUser().getMerchantId()).getProductDomain(); } } } } } } //協議://域名/項目/X目錄 ====(去掉目錄) Matcher slashMatcher = Pattern.compile("/").matcher(domain); int mIdx = 0; while(slashMatcher.find()) { mIdx++; if(mIdx == 4)break; } domain=domain.substring(0,slashMatcher.start()); /*if ("/fs".equals(domain.substring(domain.lastIndexOf("/")))) { domain = domain.substring(0, domain.lastIndexOf("/")); }*/ return domain; } // ----------------------------------------------------------------------------------- // 下載 // ---------------------------------------------------------------------------------- }
<div class="upload" id="mainPicButton"> <form method="post" enctype="multipart/form-data" target="hidden_frame" id="formImg0"> <!-- <input type="file" name="file0" id="file0" onchange="submitUpload('0')" style="width:68px;height:22px;"> --> <input type="file" name="file0" id="file0" onchange="addOnePic('#mainPicButton')" style="width:68px;height:22px;"> <input type="hidden" name="idnum" value="0"> <input type="hidden" name="suffixDir" value="05/01"/> <input type="hidden" name="cutPhoto" value="true"> <iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe> </form> </div>
<th><span>商品不少其它圖片:</span></th> <td> <div id="morePicButton"> <form method="post" enctype="multipart/form-data" target="hidden_frame" id="formImg1"> <input type="file" name="file0" id="file0" onchange="addMorePic();" style="width:68px;height:22px;"> <input type="hidden" name="idnum" value="0"> <input type="hidden" name="suffixDir" value="05/01"/> <input type="hidden" name="cutPhoto" value="true"> <iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe> </form> </div>
//全局常量 var maxNoOfPics = 5; var picPrefix = "/fs"; //圖片路徑前綴 //全局變量 var imgNum = 0; //圖片數量 var imgNo=0; //圖片ID var hasMainPic = false; var origPics = new Array(); //當更新某商品時。保存原來圖片的路徑,用於在刪除時推斷是否需要延遲刪除 //var domainStr=window.top.getLoginUser().merchantProductDomain; function getDomain(){ var domainSt=""; var userObj=window.top.getLoginUser(); if(userObj.user.userType=="0") { domainSt=userObj.publicUploadDomain; }else if(userObj.user.userType=="2"){ domainSt=userObj.merchantProductDomain; } // alert (domainSt); return domainSt; } function submitUpload(id){ $("#imgSrc" + id +"").attr("alt", "圖片上傳中……"); var imgID = id; if(id>0){ imgID = 1; } var form=document.getElementById("formImg" + imgID +""); form.method = "post"; form.idnum.value = id; var uriUp= getDomain()+"/pc/sys/photoupload/singleup?"+window.top.getLoginUser().token; form.action = uriUp; //form.action = getContextPath()+"/pc/sys/photoupload/singleup"; //必須先包括sys.js文件 //用於返回 var currentHref=window.location.href; var subHref=currentHref.substring(0, currentHref.lastIndexOf("/")); var input_domain = document.createElement("input"); input_domain.setAttribute("name", "currentDomain"); input_domain.setAttribute("value", subHref+"/callback-up.html"); input_domain.setAttribute("type", "hidden"); form.appendChild(input_domain); form.submit(); //假設已經存在的圖不是原圖,則把server中的圖片刪除 var currentPicPath = $("#imgUrl" + id +"").val(); if(!contains(origPics, currentPicPath) && currentPicPath!=""){ delImg(currentPicPath, true);//true 刪除圖片 } }; // step2: 上傳圖片。後臺回調 function callback(message) { var id=message.id; if(message.status.code=="0"){ var filePath=message.filePath; var dbFilePath=message.dbFilePath; //$("#imgUrl" + id +"").attr("value", dbFilePath); $("#imgUrl" + id +"").val(dbFilePath); $("#imgSrc" + id +"").attr("src", filePath); }else{ if(id!=0){ $("#imgSrc" + id).parent().remove(); } _message(message.status.message); //上傳錯誤提示 } }; function deleteOrigPics(photoList){ //推斷是否需要刪除原圖,假設原圖不在photoList中,則刪除 for(var i=1; i<origPics.length; i++){ var found=false; var j=0; while(!found && j<photoList.length){ if(photoList[j].url==origPics[i]){ found=true; } j++; } if(!found){ delImg(origPics[i], true); } } } /** * Author: 許繼俊, 2014-04 * 爲「不少其它圖片」添加一個圖片。加在morePicButtonId前面 * morePicButtonId: 「加入圖片」button的ID。調用此方法就在它前面加入一個圖片 * imgNo:圖片序號 * picPrefix: 圖片路徑前綴 * filePath:圖片(相對)路徑 */ //dbFilePath 用於存放數據庫, fullFilePath用於顯示圖片 function addOnePic(picButtonId, dbFilePath, fullFilePath){ if(picButtonId == "#mainPicButton"){ //假設是主圖 imgId = 0; }else{ //假設是「不少其它圖片」 imgNo++; imgNum++; imgId = imgNo; } if(picButtonId == "#mainPicButton" ){ if(hasMainPic == false){ var html = '<span class="pict">\ <img id="imgSrc' + imgId + '" width="120px" height="120px"/>\ <a class="close" onclick="removeImg(\'' + imgId + '\')"></a>\ <input type="hidden" id="imgUrl' + imgId + '"/></span>'; $(picButtonId).after(html); hasMainPic = true; } }else{ var html = '<span class="pict">\ <img id="imgSrc' + imgId + '" width="120px" height="120px"/>\ <a class="close" onclick="removeImg(\'' + imgId + '\')"></a>\ <input type="hidden" class="imgUrl" id="imgUrl' + imgId + '"/></span>'; $(picButtonId).after(html); } if(fullFilePath != undefined){ $("#imgUrl" + imgId +"").val(dbFilePath); $("#imgSrc" + imgId +"").attr("src", fullFilePath); }else{ submitUpload(imgId); //假設僅僅有一個參數。則是提交 } } //加入不少其它圖片: function addMorePic(){ if(imgNum>=maxNoOfPics){ _message("對不起。最多僅僅能上傳" + maxNoOfPics + "張圖片!json
"); return false; } addOnePic("#morePicButton"); } //刪除圖片(imgNo=0時爲主圖) function removeImg(imgNo){ var picPath=""; if($("#imgUrl"+ imgNo).val()!=undefined){ picPath=$("#imgUrl"+ imgNo).val(); $("#imgSrc" + imgNo).parent().remove(); } if(imgNo==0){ //刪除主圖 hasMainPic = false; //$("#imgSrc0").removeAttr("src"); //$("#imgSrc0").attr("alt","點擊加入圖片"); //$("#imgUrl0").removeAttr("value"); }else{ //刪除其它圖 imgNum--; } //假設是原圖。則延遲server的刪除(在提交時再刪除) if(picPath != origPics[imgNo]){ delImg(picPath,true);//true 刪除小圖 } } //刪除圖片 function delImg(path, cutPhoto){ var reqStr=null; if(cutPhoto==true){ reqStr="path="+path+"&cutPhoto=true"; }else{ reqStr="path="+path+"&cutPhoto=false"; } $.post( getContextPath()+"/pc/sys/photoupload/delimg", reqStr, function(data){ }, 'json' ); } /**推斷在數組中是否含有給定的一個變量值/對象 * array: 數組 * obj: 值/對象 */ function contains(array, obj) { for (var i = 0; i < array.length; i++) { if (array[i] === obj) { return true; } } return false; }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <script type="text/javascript"> //alert(document.domain); var returndata=self.location.hash.substring(1); if(parent.parent&&parent.parent.callback){ var message = eval('(' + returndata + ')'); parent.parent.callback(message); }else if(window.top.success){ window.top.success(returndata); }else if(parent.parent&&parent.parent.success){ parent.parent.success(returndata); } </script> </body> </html>