代码改变世界

Servet实现文件上传(fileupload)

2013-02-27 14:59  Lves Li  阅读(204)  评论(0编辑  收藏  举报

jsp使用servlet实现文件上传:

1.首先要到apache官网上下载commons-fileupload-1.2.2-bin.jar和其依赖的commons-io-2.4-bin.jar

Jsp:

<form action="UploadServlet" method="post" enctype="multipart/form-data">
    
    	username:<input type="text" name="username"><br>
    	file:<input type="file" name="file"><br>
    	file1:<input type="file" name="file1"><br>
    	<input type="submit" value="submit">
    	
    	
    </form>

Servlet:

package com.wildcat.servlet;

import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		DiskFileItemFactory factory=new DiskFileItemFactory();
		String path=request.getRealPath("/upload");
		factory.setRepository(new File(path));
		factory.setSizeThreshold(1024*1024);
		
		ServletFileUpload upload=new ServletFileUpload(factory);
		
		try{
			List <FileItem> list=(List <FileItem>)upload.parseRequest(request);
			
			for(FileItem item:list){
				String name=item.getFieldName();//调教的文本 域名
				if (item.isFormField()){//如果上传的是文本域
					
					String value=item.getString();//提交的内容
					
					System.out.println(name+" : "+value);
					request.setAttribute(name, value);
					
				}else {//如果上传的是文件
					String value=item.getName();
					//下面是对特殊浏览器的处理
					int start=value.lastIndexOf("\\");
					String fileName=value.substring(start+1);
					request.setAttribute(name, fileName);
					item.write(new File(path,fileName));
				
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		request.getRequestDispatcher("fileuploadResult.jsp").forward(request, response);
		
	}

}