最近项目中,在发布商品的时候要用到商品图片上传功能(网站前台和后台都要用到),所以单独抽出一个项目来供其他的项目进行调用 ,对外透露的接口的为两个servlet供外部上传和删除图片,利用到连个jarcommons-fileupload-1.2.1.jar,commons-io-1.4.jar
项目结构如下:
其中com.file.helper主要提供读相关配置文件的帮助类
com.file.servlet 是对外提供调用上传和删除的图片的servlet
com.file.upload 是主要提供用于上传和删除图片的接口
1、FileConst类主要是用读取文件存储路径和设置文件缓存目录 允许上传图片的最大值
01 | package com.file.helper; |
03 | import java.io.IOException; |
04 | import java.util.Properties; |
06 | public class FileConst { |
08 | private static Properties properties= new Properties(); |
11 | properties.load(ReadUploadFileType. class .getClassLoader().getResourceAsStream( "uploadConst.properties" )); |
12 | } catch (IOException e) { |
17 | public static String getValue(String key){ |
18 | String value = (String)properties.get(key); |
2、ReadUploadFileType读取允许上传图片的类型和判断上传的文件是否符合约束的文件类型
01 | package com.file.helper; |
04 | import java.io.IOException; |
05 | import java.util.ArrayList; |
07 | import java.util.Properties; |
09 | import javax.activation.MimetypesFileTypeMap; |
18 | public class ReadUploadFileType { |
21 | private static Properties properties= new Properties(); |
24 | properties.load(ReadUploadFileType. class .getClassLoader().getResourceAsStream( "allow_upload_file_type.properties" )); |
25 | } catch (IOException e) { |
35 | public static Boolean readUploadFileType(File uploadfile){ |
36 | if (uploadfile!= null &&uploadfile.length()> 0 ){ |
37 | String ext = uploadfile.getName().substring(uploadfile.getName().lastIndexOf( "." )+ 1 ).toLowerCase(); |
38 | List<String> allowfiletype = new ArrayList<String>(); |
39 | for (Object key : properties.keySet()){ |
40 | String value = (String)properties.get(key); |
41 | String[] values = value.split( "," ); |
43 | allowfiletype.add(v.trim()); |
47 | return allowfiletype.contains( new MimetypesFileTypeMap().getContentType(uploadfile).toLowerCase())&&properties.keySet().contains(ext); |
3、FileUpload主要上传和删除图片的功能
001 | package com.file.upload; |
004 | import java.util.Iterator; |
005 | import java.util.List; |
007 | import javax.servlet.http.HttpServletRequest; |
009 | import org.apache.commons.fileupload.FileItem; |
010 | import org.apache.commons.fileupload.FileUploadException; |
011 | import org.apache.commons.fileupload.disk.DiskFileItemFactory; |
012 | import org.apache.commons.fileupload.servlet.ServletFileUpload; |
014 | import com.file.helper.FileConst; |
015 | import com.file.helper.ReadUploadFileType; |
017 | public class FileUpload { |
018 | private static String uploadPath = null ; |
019 | private static String tempPath = null ; |
020 | private static File uploadFile = null ; |
021 | private static File tempPathFile = null ; |
022 | private static int sizeThreshold = 1024 ; |
023 | private static int sizeMax = 4194304 ; |
026 | sizeMax = Integer.parseInt(FileConst.getValue( "sizeMax" )); |
027 | sizeThreshold = Integer.parseInt(FileConst.getValue( "sizeThreshold" )); |
028 | uploadPath = FileConst.getValue( "uploadPath" ); |
029 | uploadFile = new File(uploadPath); |
030 | if (!uploadFile.exists()) { |
033 | tempPath = FileConst.getValue( "tempPath" ); |
034 | tempPathFile = new File(tempPath); |
035 | if (!tempPathFile.exists()) { |
036 | tempPathFile.mkdirs(); |
042 | * @return true 上传成功 false上传失败 |
044 | @SuppressWarnings ( "unchecked" ) |
045 | public static boolean upload(HttpServletRequest request){ |
048 | boolean isMultipart = ServletFileUpload.isMultipartContent(request); |
051 | /**为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。**/ |
053 | DiskFileItemFactory factory = new DiskFileItemFactory(); |
054 | factory.setSizeThreshold(sizeThreshold); |
055 | factory.setRepository(tempPathFile); |
056 | ServletFileUpload upload = new ServletFileUpload(factory); |
057 | upload.setHeaderEncoding( "UTF-8" ); |
058 | upload.setSizeMax(sizeMax); |
059 | List<FileItem> items = upload.parseRequest(request); |
061 | if (!checkFileType(items)) return false ; |
062 | Iterator<FileItem> itr = items.iterator(); |
064 | while (itr.hasNext()){ |
065 | FileItem item = (FileItem) itr.next(); |
066 | if (!item.isFormField()){ |
067 | String name = item.getName(); |
069 | File fullFile= new File(item.getName()); |
070 | File savedFile= new File(uploadPath,fullFile.getName()); |
071 | item.write(savedFile); |
075 | } catch (FileUploadException e) { |
078 | } catch (Exception e) { |
084 | System.out.println( "the enctype must be multipart/form-data" ); |
091 | * @param filePath 文件路径数组 |
093 | public static void deleteFile(String [] filePath){ |
094 | if (filePath!= null && filePath.length> 0 ){ |
095 | for (String path:filePath){ |
096 | String realPath = uploadPath+path; |
097 | File delfile = new File(realPath); |
098 | if (delfile.exists()){ |
108 | * @param filePath 单个文件路径 |
110 | public static void deleteFile(String filePath){ |
111 | if (filePath!= null && ! "" .equals(filePath)){ |
112 | String [] path = new String []{filePath}; |
122 | private static Boolean checkFileType(List<FileItem> items){ |
123 | Iterator<FileItem> itr = items.iterator(); |
124 | while (itr.hasNext()){ |
125 | FileItem item = (FileItem) itr.next(); |
126 | if (!item.isFormField()){ |
127 | String name = item.getName(); |
129 | File fullFile= new File(item.getName()); |
130 | boolean isType = ReadUploadFileType.readUploadFileType(fullFile); |
131 | if (!isType) return false ; |
4、FileUploadServlet上传文件servlet 供外部调用
01 | package com.file.servlet; |
03 | import java.io.IOException; |
05 | import javax.servlet.ServletException; |
06 | import javax.servlet.http.HttpServlet; |
07 | import javax.servlet.http.HttpServletRequest; |
08 | import javax.servlet.http.HttpServletResponse; |
10 | import com.file.upload.FileUpload; |
13 | @SuppressWarnings ( "serial" ) |
14 | public class FileUploadServlet extends HttpServlet { |
16 | public void doGet(HttpServletRequest request, HttpServletResponse response) |
17 | throws ServletException, IOException { |
18 | this .doPost(request, response); |
22 | public void doPost(HttpServletRequest request, HttpServletResponse response) |
23 | throws ServletException, IOException { |
24 | FileUpload.upload(request); |
5、DeleteFileServlet删除图片供外部调用
01 | package com.file.servlet; |
03 | import java.io.IOException; |
05 | import javax.servlet.ServletException; |
06 | import javax.servlet.http.HttpServlet; |
07 | import javax.servlet.http.HttpServletRequest; |
08 | import javax.servlet.http.HttpServletResponse; |
10 | import com.file.upload.FileUpload; |
12 | @SuppressWarnings ( "serial" ) |
13 | public class DeleteFileServlet extends HttpServlet { |
14 | public void doGet(HttpServletRequest request, HttpServletResponse response) |
15 | throws ServletException, IOException { |
16 | this .doPost(request, response); |
19 | public void doPost(HttpServletRequest request, HttpServletResponse response) |
20 | throws ServletException, IOException { |
21 | String [] file = request.getParameterValues( "fileName" ); |
22 | FileUpload.deleteFile(file); |
6、allow_upload_file_type.properties
gif=image/gif
jpg=mage/jpg,image/jpeg,image/pjpeg
png=image/png,image/x-pngimage/x-png,image/x-png
bmp=image/bmp
7、uploadConst.properties
sizeThreshold=4096
tempPath=c\:\\temp\\buffer\\
sizeMax=4194304
uploadPath=c\:\\upload\\
8外部调用
index.jsp
01 | <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> |
03 | String path = request.getContextPath(); |
04 | String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; |
07 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> |
10 | < base href="<%=basePath%>"> |
12 | < title >My JSP 'index.jsp' starting page</ title > |
13 | < meta http-equiv = "pragma" content = "no-cache" > |
14 | < meta http-equiv = "cache-control" content = "no-cache" > |
15 | < meta http-equiv = "expires" content = "0" > |
16 | < meta http-equiv = "keywords" content = "keyword1,keyword2,keyword3" > |
17 | < meta http-equiv = "description" content = "This is my page" > |
24 | < form name = "myform" action = "http://xxx.com/FileUploadServlet" method = "post" enctype = "multipart/form-data" > |
26 | < input type = "file" name = "myfile" >< br > |
28 | < input type = "submit" name = "submit" value = "Commit" > |