注意 jsp页面中file选择 的要有属性 name='file'
package com.webserver.webservice; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.apache.catalina.core.ApplicationPart; /** * Servlet implementation class UpLoadServlet * author:chuanyuBai 2014/07/21 */ @MultipartConfig(location = "D:/upload", fileSizeThreshold = 1024) public class PCMUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public PCMUploadServlet() { super(); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); try{ //获取多文件 List<Part> partlist = (List<Part>) request.getParts(); //获取单文件文件部件part Part part = request.getPart("file"); //获取文件名称的两种方式 //方式一 String filename1 = ((ApplicationPart)part).getFilename(); //方式二 //获取文件服务器头部信息 String h = part.getHeader("content-disposition"); String filename = h.substring(h.lastIndexOf("=") + 2, h.length() - 1); String root = request.getServletContext().getRealPath("/upload"); File f=new File(root); f.mkdir(); //删除生成的中间文件 part.delete(); part.write(root+"/"+filename); }catch(Exception e){ System.out.println(e.getMessage()); } } }