Servlet使用Apache fileupload和io包处理文件上传

需要去apache官网下载commons-fileupload和commons-io两个组件,导入项目中。上传的表单就不贴了,各种语言都一样,下面是处理上传的Servlet:

package com.servlet;

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

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

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;

public class UploadServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		DiskFileItemFactory factory=new DiskFileItemFactory();
		String path=req.getRealPath("/upload/");
		String tempDir=req.getRealPath("/temp/");
		
		//文件临时目录,默认为System.getProperty("java.io.tmpdir")
		factory.setRepository(new File(tempDir));
		//设置文件大小上限,当文件大于此值时,先存储到临时目录,否则存在内存中
		factory.setSizeThreshold(1024*100);
		ServletFileUpload sfu=new ServletFileUpload(factory);
		try {
			List list=sfu.parseRequest(req);
			PrintWriter out=resp.getWriter();
			resp.setContentType("text/html; charset=utf-8");   
			 resp.setCharacterEncoding("utf-8");   
			for(FileItem item:list)
			{
				if(item.isFormField())
				{
					out.println(item.getFieldName()+"="+item.getString()+"  ");
				}else{
					try {
						String value=item.getName();
						int start=value.lastIndexOf("//");
						String filename=value.substring(start+1);
						//使用write方法写入文件,自动处理临时文件
						item.write(new File(path,filename));
						
						//使用文件流写入文件,需要手工删除临时文件,
						FileOutputStream fos=new FileOutputStream(new File(path,"bb.jpg"));
						InputStream is=item.getInputStream();
						byte[] bs=new byte[1024];
						int len=0;
						while((len=is.read(bs, 0, 1024))>-1)
						{
							fos.write(bs,0,len);
						}
						fos.close();
						is.close();
						
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
		
}

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记