package com.wildcat.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; 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); // 这里就是中文文件名处理的代码,其实只有一行,serheaderencoding就可以了 upload.setHeaderEncoding("utf-8"); 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)); /* OutputStream os=new FileOutputStream(new File(path,fileName)); InputStream in=item.getInputStream(); byte [] buffer=new byte[400]; long sumL=item.getSize(); int length=0; double sumR = 0; while((length=in.read(buffer))!=-1){ sumR+=length; //下面百分比可以显示进度 System.out.println(sumR/sumL); os.write(buffer, 0, length); } in.close(); os.close(); */ } } }catch(Exception e){ e.printStackTrace(); } request.getRequestDispatcher("fileuploadResult.jsp").forward(request, response); } }