最近項目中,在發佈商品的時候要用到商品圖片上傳功能(網站前臺和後臺都要用到),因此單獨抽出一個項目來供其餘的項目進行調用 ,對外透露的接口的爲兩個servlet供外部上傳和刪除圖片,利用到連個jarcommons-fileupload-1.2.1.jar,commons-io-1.4.jarcss
其中com.file.helper主要提供讀相關配置文件的幫助類html
com.file.servlet 是對外提供調用上傳和刪除的圖片的servletjava
com.file.upload 是主要提供用於上傳和刪除圖片的接口apache
一、FileConst類主要是用讀取文件存儲路徑和設置文件緩存目錄 容許上傳圖片的最大值數組
package com.file.helper; import java.io.IOException; import java.util.Properties; public class FileConst { private static Properties properties= new Properties(); static{ try { properties.load(ReadUploadFileType.class.getClassLoader().getResourceAsStream("uploadConst.properties")); } catch (IOException e) { e.printStackTrace(); } } public static String getValue(String key){ String value = (String)properties.get(key); return value.trim(); } }
二、ReadUploadFileType讀取容許上傳圖片的類型和判斷上傳的文件是否符合約束的文件類型
package com.file.helper; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.activation.MimetypesFileTypeMap; /** * 讀取配置文件 * @author Owner * */ public class ReadUploadFileType { private static Properties properties= new Properties(); static{ try { properties.load(ReadUploadFileType.class.getClassLoader().getResourceAsStream("allow_upload_file_type.properties")); } catch (IOException e) { e.printStackTrace(); } } /** * 判斷該文件是否爲上傳的文件類型 * @param uploadfile * @return */ public static Boolean readUploadFileType(File uploadfile){ if(uploadfile!=null&&uploadfile.length()>0){ String ext = uploadfile.getName().substring(uploadfile.getName().lastIndexOf(".")+1).toLowerCase(); List<String> allowfiletype = new ArrayList<String>(); for(Object key : properties.keySet()){ String value = (String)properties.get(key); String[] values = value.split(","); for(String v:values){ allowfiletype.add(v.trim()); } } // "Mime Type of gumby.gif is image/gif" return allowfiletype.contains( new MimetypesFileTypeMap().getContentType(uploadfile).toLowerCase())&&properties.keySet().contains(ext); } return true; } }
三、FileUpload主要上傳和刪除圖片的功能
package com.file.upload; import java.io.File; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.file.helper.FileConst; import com.file.helper.ReadUploadFileType; public class FileUpload { private static String uploadPath = null;// 上傳文件的目錄 private static String tempPath = null; // 臨時文件目錄 private static File uploadFile = null; private static File tempPathFile = null; private static int sizeThreshold = 1024; private static int sizeMax = 4194304; //初始化 static{ sizeMax = Integer.parseInt(FileConst.getValue("sizeMax")); sizeThreshold = Integer.parseInt(FileConst.getValue("sizeThreshold")); uploadPath = FileConst.getValue("uploadPath"); uploadFile = new File(uploadPath); if (!uploadFile.exists()) { uploadFile.mkdirs(); } tempPath = FileConst.getValue("tempPath"); tempPathFile = new File(tempPath); if (!tempPathFile.exists()) { tempPathFile.mkdirs(); } } /** * 上傳文件 * @param request * @return true 上傳成功 false上傳失敗 */ @SuppressWarnings("unchecked") public static boolean upload(HttpServletRequest request){ boolean flag = true; //檢查輸入請求是否爲multipart表單數據。 boolean isMultipart = ServletFileUpload.isMultipartContent(request); //若果是的話 if(isMultipart){ /**爲該請求建立一個DiskFileItemFactory對象,經過它來解析請求。執行解析後,全部的表單項目都保存在一個List中。**/ try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(sizeThreshold); // 設置緩衝區大小,這裏是4kb factory.setRepository(tempPathFile);// 設置緩衝區目錄 ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8");//解決文件亂碼問題 upload.setSizeMax(sizeMax);// 設置最大文件尺寸 List<FileItem> items = upload.parseRequest(request); // 檢查是否符合上傳的類型 if(!checkFileType(items)) return false; Iterator<FileItem> itr = items.iterator();//全部的表單項 //保存文件 while (itr.hasNext()){ FileItem item = (FileItem) itr.next();//循環得到每一個表單項 if (!item.isFormField()){//若是是文件類型 String name = item.getName();//得到文件名 包括路徑啊 if(name!=null){ File fullFile=new File(item.getName()); File savedFile=new File(uploadPath,fullFile.getName()); item.write(savedFile); } } } } catch (FileUploadException e) { flag = false; e.printStackTrace(); }catch (Exception e) { flag = false; e.printStackTrace(); } }else{ flag = false; System.out.println("the enctype must be multipart/form-data"); } return flag; } /** * 刪除一組文件 * @param filePath 文件路徑數組 */ public static void deleteFile(String [] filePath){ if(filePath!=null && filePath.length>0){ for(String path:filePath){ String realPath = uploadPath+path; File delfile = new File(realPath); if(delfile.exists()){ delfile.delete(); } } } } /** * 刪除單個文件 * @param filePath 單個文件路徑 */ public static void deleteFile(String filePath){ if(filePath!=null && !"".equals(filePath)){ String [] path = new String []{filePath}; deleteFile(path); } } /** * 判斷上傳文件類型 * @param items * @return */ private static Boolean checkFileType(List<FileItem> items){ Iterator<FileItem> itr = items.iterator();//全部的表單項 while (itr.hasNext()){ FileItem item = (FileItem) itr.next();//循環得到每一個表單項 if (!item.isFormField()){//若是是文件類型 String name = item.getName();//得到文件名 包括路徑啊 if(name!=null){ File fullFile=new File(item.getName()); boolean isType = ReadUploadFileType.readUploadFileType(fullFile); if(!isType) return false; break; } } } return true; } }
四、FileUploadServlet上傳文件servlet 供外部調用
package com.file.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.file.upload.FileUpload; @SuppressWarnings("serial") public class FileUploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FileUpload.upload(request); } }
五、DeleteFileServlet刪除圖片供外部調用
package com.file.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.file.upload.FileUpload; @SuppressWarnings("serial") public class DeleteFileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String [] file = request.getParameterValues("fileName"); FileUpload.deleteFile(file); } }
六、allow_upload_file_type.properties緩存
gif=image/gifjsp
jpg=mage/jpg,image/jpeg,image/pjpegpost
png=image/png,image/x-pngimage/x-png,image/x-png網站
bmp=image/bmpui
七、uploadConst.properties
sizeThreshold=4096
tempPath=c\:\\temp\\buffer\\
sizeMax=4194304
uploadPath=c\:\\upload\\
8外部調用
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form name="myform" action="http://xxx.com/FileUploadServlet" method="post" enctype="multipart/form-data"> File: <input type="file" name="myfile"><br> <br> <input type="submit" name="submit" value="Commit"> </form> </body> </html>