文件上传对应的一个Servlet类

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;



public class Upload extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static  String baseDir;
	private static  String allowedType;
	private static  SimpleDateFormat dirFormat;
	private static  SimpleDateFormat fileFormat;
	private static  boolean debug = false;
	
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		
	 debug = (new Boolean(getInitParameter("debug"))).booleanValue();//根据XML的配置判断是否是debug模式
	 if(debug)
		 System.out.println("\r\n---- UploaderServlet initialization started ----");
	 
	 dirFormat = new SimpleDateFormat("yyyyMM");
	 fileFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	 
	 baseDir = getInitParameter("baseDir");
	 if(baseDir==null){
		 baseDir = "/User/";
	 }
	 
	 String realBaseDir = getServletContext().getRealPath(baseDir);//得到完整的文件存储路径
	 if(debug)
		 System.out.println("-----realBaseDir-----"+realBaseDir);
	 
	 File baseFile = new File(realBaseDir);//创建realBaseDir文件
	 if(!baseFile.exists())               //如果该文件不存在,创建该文件。
		 baseFile.mkdirs();
	 
	 allowedType = getInitParameter("allow_type");
	 if(debug){
		 
	     System.out.println(getInitParameter("allow_type"));
	     System.out.println("\r\n---- UploaderServlet initialization ended ----");
	 }
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		if(debug)
			System.out.println("------begin  post method-----");
		
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		response.setHeader("Cache-Control", "no-cache");
		
		Date time = new Date();
		
		String filePath = baseDir+dirFormat.format(time);//在文件夹下面根据时间创建文件夹保存图片
		if(debug)
			System.out.println("-------filepath-----"+filePath);
		String fileDirPath = getServletContext().getRealPath(filePath);
		if(debug)
			System.out.println("-------fileDirPath------"+fileDirPath);
		    //System.out.println(request.getContextPath());get the name of web application
		File fileDir = new File(fileDirPath);//创建文件夹
		if(!fileDir.exists()){
			fileDir.mkdirs();
		}
		
		PrintWriter out = response.getWriter();
		
		//User fileUpload class of file commons to upload files
		DiskFileItemFactory dfif = new DiskFileItemFactory();
		dfif.setSizeThreshold(1024*100);                                      //保存在内存还是硬盘的临界值
		dfif.setRepository(new File(request.getRealPath("/")+baseDir+"temp"));//创建临时文件夹
		
		ServletFileUpload sfu = new ServletFileUpload(dfif);                 //根据DiskFileItemFactory创建ServletFileUpload对象
		sfu.setSizeMax(1024*1024*4);                                         //一次上传的文件最大值
		
		List fileList = null;
		
		try{
			List items = sfu.parseRequest(request);                     //ServletFileUpload解析请求对象
			Map  fields=new HashMap();
			Iterator iterators = items.iterator();
			while(iterators.hasNext()){
				FileItem fileItem = (FileItem)iterators.next();
				if(fileItem.isFormField()){                         //如果是普通的文本对象
					fields.put(fileItem.getFieldName(), fileItem.getString());
				}else{                                              //文件上传表单域
					long size = fileItem.getSize();             //得到上传文件的大小 
					String fileLocalName = fileItem.getName();  //上传文件的名字,原来的名字
					if("".equals(fileLocalName)||size==0){      //处理没有上传文件的情况
						out.println("请重新操作,选择上传的文件");
						out.println("<form><input type='button' value='Click to return ' onClick='window.history.go(-1)'/> </form>");
						return ;
					}
					if(debug)
						System.out.println("---------file local name------"+fileLocalName);
					fileLocalName = fileLocalName.replace("\\", "/");//对文件名字解析,注意转义符
					if(debug)
						System.out.println("---------file local name------"+fileLocalName);
					String[]  pathParts = fileLocalName.split("/");
					String fileName = pathParts[pathParts.length-1];
					if(debug)
						System.out.println("----------file name------"+fileName);
					String ext1=fileLocalName.substring(fileLocalName.lastIndexOf(".")+1);//这一句和下面的ext相同的效果
					if(debug)
					   System.out.println("-------ext1-----"+ext1);
					String ext = fileName.substring(fileName.lastIndexOf(".")+1);
					if(debug)
						System.out.println("------ext------"+ext);
					fileName = fileFormat.format(time)+"."+ext;
					if(debug)
						System.out.println("----------file name------"+fileName);
					
					File fileToSave = new File(fileDirPath,fileName);//创建文件
					System.out.println("--------1");
					String fileUrl = fileDirPath +"/"+ fileName;     //文件路径
					if(debug)
						System.out.println("------fileUrl-----"+fileUrl);
					System.out.println("--------3");
					if(!extAllowed(allowedType,ext)){                //判断是否是XmL文件中定义的合法类型
						System.out.println(4);
						out.println("Type "+ext+" is not allowed to upload");
						out.println("<form><input type='button' value='Click to return ' onClick='window.history.go(-1)'/> </form>");
					    return;
					}
					System.out.println("--------2");
					try{
						fileItem.write(fileToSave);               //将内容写到指定的文件中,这个文件必须是一个已经创建的
						out.println("file has already been uploaded;");
						out.println("<a href='index.jsp'>Click to return</a>");
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
		}catch(FileUploadException e){                               //处理上传中的异常
			if(e instanceof SizeLimitExceededException){
				out.println("the size is too big<p />");
				out.println("<form><input type='button' value='Click to return ' onClick='index.jsp'/> </form>");
				return ;
			}
			e.printStackTrace();
		}
		
		
		
//		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
//		out.println("<HTML>");
//		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
//		out.println("  <BODY>");
//		out.print("    This is ");
//		out.print(this.getClass());
//		out.println(", using the POST method");
//		out.println("  </BODY>");
//		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Returns information about the servlet, such as 
	 * author, version, and copyright. 
	 *
	 * @return String information about this servlet
	 */
	public String getServletInfo() {
		return "This is my default servlet created by Eclipse";
	}
	public boolean extAllowed(String fileTypes,String str ){     //判断文件类型是否是合法类型的方法
		
		String[] allowList = fileTypes.split(",");
		boolean isexist = false;
		for(String al:allowList){
			if(al.equals(str))
				isexist = true;
		}
		return isexist;
	}

	

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值