在Servlet中要实现文件上传,需要以下第三方架包
jsp页面的表单应该设为post方式提交,并且设置 enctype="multipart/form-data" ,默认的为 enctype="application/x-www-form-urlencoded"
${message}为显示上传操作结果通知。
${message}
后台实现如下,可以判断上传类型,注意:文件上传名重复,会覆盖原有文件,所以自己要加判断
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String[] allowTypes = new String[]{"txt","doc","docx","xls","xlsx","ppt","pdf","xml","html"}; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String path = request.getSession().getServletContext().getRealPath("/files"); System.out.println(path); try { Listitems = (List ) upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if(item.isFormField()){ System.out.println("文本信息"); }else{ if (item.getName() != null && !item.getName().equals("")) { String name = item.getName(); String type = name.substring(name.lastIndexOf('.')+1); boolean flag = false; for(String at:allowTypes){ if(at.equals(type)){ flag = true; } } if(flag==false){ System.out.println("文件格式不支持"); request.setAttribute("message", "文件格式不支持"); }else{ int start = name.lastIndexOf("\\"); String filename = name.substring(start+1); File file = new File(path+"/"+filename); item.write(file); request.setAttribute("message", "文件上传成功"); } }else{ System.out.println("请选择待上传文件"); request.setAttribute("message", "请选择待上传文件"); } } } }catch (Exception e) { e.printStackTrace(); request.setAttribute("message", "文件上传失败"); } request.getRequestDispatcher("upload.jsp").forward(request, response); }
web.xml文件配置