文件上传Servlet实例

 
package com.hbsi.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.FileUploadBase.FileUploadIOException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet3 extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UploadServlet3() {
		super();
	}

	/**
	 * 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 {
		doPost(request, response);
	}

	/**
	 * 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
	 */
	private List fileType=Arrays.asList(".jsp",".jar",".txt");
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//文件上传
		
		try {
			//(1)创建一个解析器工厂---FileItem对象
			DiskFileItemFactory factory=new DiskFileItemFactory();
			
			factory.setRepository(new File(this.getServletContext().getRealPath("/temp")));//将临时文件存在指定路径
			//(2)得到解析器
			ServletFileUpload upload=new ServletFileUpload(factory);
			upload.setHeaderEncoding("utf-8");
			upload.setFileSizeMax(1024*1024);
			upload.setProgressListener(new ProgerssHandle());//文件上传进度监听器
			//(3)对请求进行解析,有几个输入项,就会解析几个FileItem对象
			List<FileItem> list=upload.parseRequest(request);
			//(4)迭代list集合,对里边的每一个输入想进行处理(获取每一个输入项)
			for(FileItem item:list){
				//(5)判断输入的类型
				if(item.isFormField()){
					//普通输入项
					String inputName=item.getFieldName();
					String inputValue=item.getString();
					inputValue=new String(inputValue.getBytes("iso8859-1"),"utf-8");
					System.out.println(inputName+"  "+inputValue);
					//普通的输入有乱码如何解决
				}else{
					//上传文件的输入项
					String filename=item.getName();//上传文件的文件名字
					if(!filename.trim().equals("")){//截取掉名字两边的空串,和空串比较看是否为空串决定是否执行程序
					
					filename=filename.substring(filename.lastIndexOf("\\")+1);//获取文件名(不包括路径)
					String ext=filename.substring(filename.lastIndexOf("."));//获取扩展名
					if(!fileType.contains(ext)){
						request.setAttribute("message","上传失败--文件类型只能是jpg,txt,jar");
						request.getRequestDispatcher("/message.jsp").forward(request, response);
						return;
					}
					
					//得到输出留对象
					InputStream is=item.getInputStream();
					//首先确定上传文件要保存在那个目录下
					String savePath=this.getServletContext().getRealPath("WEB-INF/Upload");
					//upload下建多级的子目录
					savePath=generateFilePath(savePath,filename);
					 //对文件名进行了加工
					filename=UUID.randomUUID().toString()+"_"+filename;
					//构建输出流对象
					FileOutputStream fos=new FileOutputStream(savePath+"\\"+filename);
					byte[] buff=new byte[1024];
					int len=0;
					while((len=is.read(buff))>0){
						fos.write(buff,0,len);
					}
					is.close();
					fos.close();
					item.delete();//删除的是临时文件
					}
				}
			}
			request.setAttribute("message", "上传成功");
		
		}catch(FileUploadBase.FileUploadIOException e){
			request.setAttribute("message","上传文件太大不能超过1M");
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("message","上传失败");
		}
		
		request.getRequestDispatcher("/message.jsp").forward(request, response);

		}
public String generateFilePath(String path,String filename){
	// 产生目录结构的算法:hash目录
	int dir1=filename.hashCode() & 0x0f;//一级目录名
	int dir2=filename.hashCode() >>4 & 0x0f;
	String savePath=dir1+"\\"+dir2+"\\";
	File f=new File(savePath);
	if(!f.exists()){//判断目录是否存在
		f.mkdirs();//多级目录结构创建
	}
	
	return savePath;
	
}
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
	class ProgerssHandle implements ProgressListener{
		

		public void update(long arg0, long arg1, int arg2) {
			// TODO Auto-generated method stub
			System.out.println("已经处理了"+arg0+"数据,总数据是"+arg1+"正在处理第"+arg2+"个数据");

		}
	}
} 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值