<%@page import="java.io.File"%> <%@page import="org.apache.commons.fileupload.FileItem"%> <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%> <%@page import="org.apache.commons.fileupload.FileItemFactory"%> <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% request.setCharacterEncoding("utf-8"); //1.判断是不是文件上传表单 boolean ismultipart = ServletFileUpload.isMultipartContent(request); if (ismultipart) { //2.创建文件上传工厂 FileItemFactory fac = new DiskFileItemFactory(); //3.创建文件上传对象 ServletFileUpload fileUpload = new ServletFileUpload(fac); //4.解析请求 List<FileItem> fileItemList = fileUpload.parseRequest(request); //5.遍历集合,获取相应的数据 try { for (FileItem item : fileItemList) { //判断是普通表单数据还是文件数据 if (item.isFormField()) { //true为普通表单 //获取提交过来表单name属性值 //文件上传中不能用下列方法取数据 //request.getParameter("userName"); String filedName = item.getFieldName(); if (filedName.equals("userName")) { //封装用户信息 System.out.println("用户名" + item.getString("utf-8")); } else if (filedName.equals("userPwd")) { System.out.println("密码" + item.getString("utf-8")); } } else { //false为文件表单 //6.获取文件名(全路径) String fullFileName = item.getName(); //out.print(fullFileName); File file1 = new File(fullFileName); //只获取文件名,不包含路径 String fileName = file1.getName(); //7.根据虚拟路径来获取物理路径 String uploadPath = application .getRealPath("upload/"); File file2 = new File(uploadPath, fileName); item.write(file2); out.print("上传成功!"); }//else }//for } catch (Exception ex) { ex.printStackTrace(); out.print("上传失败"); } } %>