package servlet; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; 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.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import entit.News; import service.NewService; import service.impl.NewServiceImpl; /** * Servlet implementation class newsServlet */ @WebServlet("/uploadFileServlet") public class newsServlet extends HttpServlet { private static final long serialVersionUID = 1L; public newsServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String uplaodPath = null; response.setCharacterEncoding("utf-8"); News news = new News(); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); boolean flag = upload.isMultipartContent(request); if (flag) { // 证明文件上传请求 try { // 获取的是所有的表单元素 包括普通元素和文件元素 List<FileItem> items = upload.parseRequest(request); // List<FileItem> 是一个元素吗? 是4个??有可能N个??? 遍历!!!! Iterator<FileItem> its = items.iterator(); while (its.hasNext()) { // 遍历集合 // 获取一个一个的元素 FileItem item = its.next(); if (item.isFormField()) { // 普通字段 String fileName = item.getFieldName(); // 获取name属性值 if (fileName.equals("id")) { news.setNewsid(Integer.parseInt(item.getString("utf-8"))); } else if (fileName.equals("title")) { news.setNewstitle(item.getString("utf-8")); } else if (fileName.equals("author")) { news.setNewssummary(item.getString("utf-8")); } } else { // 文件元素 // 获取服务器所在的位置 uplaodPath = request.getSession().getServletContext().getRealPath("uploadFiles/"); File file = new File(uplaodPath); if (!file.exists()) { // 如果创建文件夹不存杂 则创建 file.mkdirs(); } // 获取上传文件的名称 String fileName = item.getName(); // 用户有可能不上传文件 if (!fileName.equals("") && fileName != null) { File uploadFile = new File(fileName); // 获取上传文件 File saveFile = new File(uplaodPath, uploadFile.getName());// 拼接文件位置 // 真正的上传 item.write(saveFile); news.setNewspic(uploadFile.getName()); // 给对象赋值 } } } NewService service = new NewServiceImpl(); int num = service.addNew(news); if (num > 0) { System.out.println(uplaodPath); } else { System.out.println("新增失败"); } } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("不是文件上传请求!"); } } }
使用的时候需要导入俩个jar