Java文件上传组件 common-fileUpload 使用教程

最近项目中,在发布商品的时候要用到商品图片上传功能(网站前台和后台都要用到),因此单独抽出一个项目来供其余的项目进行调用 ,对外透露的接口的为两个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>
相关文章
相关标签/搜索