jsp使用servlet實現文件上傳: 1.首先要到apache官網上下載commons-fileupload-1.2.2-bin.jar和其依賴的commons-io-2.4-bin.jar Jsp: [html] <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: [java] 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)); } www.2cto.com } }catch(Exception e){ e.printStackTrace(); } request.getRequestDispatcher("fileuploadResult.jsp").forward(request, response); } }