举例说明:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPEhtml PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <metahttp-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>upload file</title> </head> <body> <form action="GetPost" method="post" enctype="multipart/form-data"> <input name="name" type="text"> <input name="sex" type="text"> <input name="file" type="file"> <input type="submit" value="提交"> </form> </body> </html>
package com.servlet; import java.io.File; import java.io.IOException; 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.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Servlet implementation class GetPost */ public class GetPost extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { String name = request.getParameter("name"); String sex = request.getParameter("sex"); System.out.println("name = " + name); System.out.println("sex = " + sex); } protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { String dir =request.getSession().getServletContext().getRealPath("/upload"); // String dir = "C:/upload"; File dirFile = new File(dir); if (!dirFile.exists()) { dirFile.mkdirs(); } try { FileItemFactory factory = newDiskFileItemFactory(); ServletFileUpload fileUpload = newServletFileUpload(factory); @SuppressWarnings("unchecked") List<FileItem> items = fileUpload.parseRequest(request); for (FileItem item : items) { //不是文件类型 if (item.isFormField()) { String name =item.getFieldName(); String value =item.getString(); System.out.println(name +" = " + value); } else { //文件类型 System.out.println(dir); System.out.println(item.getName()); String longFileName = item.getName(); char indexChar = '\\'; String fileName = item.getName().substring(longFileName.lastIndexOf(indexChar) + 1, longFileName.length()); System.out.println(fileName); //注:如果fileName带路径,则会报错(文件名、目录名或卷标语法不正确) //如:fileName = “C:/upload/xxx.txt”就会报错,此时可以截取fileName的最后一部分,结果就不会再报错 File saveFile = new File(dirFile,fileName); item.write(saveFile); } } } catch (Exception e) { e.printStackTrace(); } } doGet(request, response); } }