你的位置:首页 > Java教程

[Java教程]使用servlet实现文件上传


 1 package com.zhanghaobo.fileupload; 2  3 import java.io.File; 4 import java.io.IOException; 5 import java.util.List; 6  7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest;10 import javax.servlet.http.HttpServletResponse;11 12 import org.apache.commons.fileupload.FileItem;13 import org.apache.commons.fileupload.disk.DiskFileItemFactory;14 import org.apache.commons.fileupload.servlet.ServletFileUpload;15 16 public class UploadServlet extends HttpServlet {17   @Override18   protected void doPost(HttpServletRequest req, HttpServletResponse resp)19       throws ServletException, IOException {20     DiskFileItemFactory factory=new DiskFileItemFactory();21     22     String realPath=req.getRealPath("/upload");23     24     //物理缓存存放地25     factory.setRepository(new File(realPath));26     27     //设置内存存放大小28     factory.setSizeThreshold(1024*1024);29     30     ServletFileUpload upload=new ServletFileUpload(factory);31     //FileItem 可以表示文件(file)也可以表示文本域(form item) 有一个isFormField方法判断是否是表单32     try{33       List<FileItem> list=(List<FileItem>)upload.parseRequest(req);34       for(FileItem item:list){35         String name=item.getFieldName();36         if(item.isFormField()){37           String value=item.getString();38           req.setAttribute(name, value);39         }else{40           String value=item.getName();41           int start=value.lastIndexOf("\\");42           String fileName=value.substring(start+1);43           req.setAttribute(name, fileName);44           //上传文件存放地45           item.write(new File(realPath,fileName));46         }47       }48     }catch(Exception e){49       e.printStackTrace();50     }51     52     req.getRequestDispatcher("showResult.jsp").forward(req, resp);53   }54 }