package com.kayson.UDServlet; 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 FileUploadServlet extends HttpServlet { private static String path = ""; //定义一个静态的路径变量 public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { path = this.getServletContext().getRealPath("/upload"); //获取表单里的上传文件的路径在接上/upload try { DiskFileItemFactory factory = new DiskFileItemFactory(); //创建一个磁盘工厂对象 ServletFileUpload up = new ServletFileUpload(factory); //创建一个上传对象(在自己导的fileupload包中) List<FileItem> ls = up.parseRequest(request); //将对应的上传的文件数据(属性)保存到数组中 for (FileItem fileItem : ls) { //开始将上传的文件写入服务器上的磁盘上 if (fileItem.isFormField()) { String FieldName = fileItem.getFieldName(); //getName()返回的是文件名字 普通域没有文件 返回NULL // String Name = fileItem.getName(); String Content = fileItem.getString("gbk"); request.setAttribute(FieldName, Content); } else { String nm = fileItem.getName().substring( fileItem.getName().lastIndexOf("\\") + 1); //获取上传文件名 System.out.println(nm); System.out.println(fileItem.getName()); File mkr = new File(path, nm); //在path指定的路径下创建mn这个文件 if (mkr.createNewFile()) { //创建文件成功就把文件写入磁盘中 fileItem.write(mkr); //文件写入磁盘 } request.setAttribute("result", "上传文件成功!"); } } } catch (Exception e) { e.printStackTrace(); request.setAttribute("result", "上传失败,请查找原因,重新再试!"); } //有成功或失败跳转到自己指定的页面 request.getRequestDispatcher("/pages/admin/annex-manager.jsp").forward(request, response); } }