1.首先我们应该为上传的文件建一个存放的位置,一般位置分为临时和真是文件夹,那我们就需要获取这俩个文件夹的绝对路径,在servlet中我们可以这样做
ServletContext application = this.getServletContext(); String tempDirectory = application.getRealPath(Constant.TEMP_DIRECTORY) + "https://www.jb51.net/"; String realDirectory = application.getRealPath(Constant.REAL_DIRECTORY) + "https://www.jb51.net/";
然后建立文件工厂即仓库一个参数表示存放多大后flush,
复制代码 代码如下:
FileItemFactory factory = new DiskFileItemFactory(Constant.SIZE_THRESHOLD,new File(tempDirectory));
ServletFileUpload upload = new ServletFileUpload(factory);
2.对上传的文件进行设定
upload.setSizeMax(500*1024*1024);//设置该次上传最大值为500M3,.解析请求正文,获取上传文件,不抛出异常则写入真是路径
List<FileItem> list = upload.parseRequest(request); Iterator<FileItem> iter = list.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); //item.isFormField()用来判断当前对象是否是file表单域的数据 如果返回值是true说明不是 就是普通表单域 if(item.isFormField()){ System.out.println( "普通表单域" +item.getFieldName()); System.out.println(item.getString("utf-8")); }else{ //System.out.println("file表单域" + item.getFieldName()); /* * 只有file表单域才将该对象中的内容写到真实文件夹中 */ String lastpath = item.getName();//获取上传文件的名称 lastpath = lastpath.substring(lastpath.lastIndexOf(".")); String filename = UUID.randomUUID().toString().replace("-", "") + lastpath; item.write(new File(realDirectory+filename));
package com.lanyou.support.servlet; 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 net.sf.json.JSONObject; 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; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts2.ServletActionContext; public class FileUpload extends HttpServlet { private static final long serialVersionUID = 1L; private static Log logger = LogFactory.getLog(FileUpload.class); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 类型 1事件上传文件 2apk String t = req.getParameter("t") == null ? "1" : req.getParameter("t") .trim(); String path = ""; JSONObject ob = new JSONObject(); try { //将请求消息中的每一个项目封装成单独DiskFileItem对象的任务 //当上传的文件项目比较小时保存在内存中,比较大时保存在磁盘零时文件夹中 //建立文件仓库(工厂) FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); //对上传的文件进行设定 servletFileUpload.setSizeMax(1024 * 1024 * 2);// 最大2M数据 servletFileUpload.setFileSizeMax(2 * 1024 * 1024); servletFileUpload.setHeaderEncoding("UTF-8");// 解决文件名乱码的问题 //解析请求正文,获取上传文件,不抛出异常则写入真实路径 //根据请求获取文件列表 List<FileItem> fileItemsList = servletFileUpload.parseRequest(req); //从文件列表中取出单独的文件对象 for (FileItem item : fileItemsList) { //判断该文件是否是普通的表单类型,该处是file类型进入判断 if (!item.isFormField()) { //如果上传的文件大于指定的大小则return if (item.getSize() > 2 * 1024 * 1024) { return; } // System.out.println("上传文件的大小:"+item.getSize()); // System.out.println("上传文件的类型:"+item.getContentType()); // System.out.println("上传文件的名称:"+item.getName()); //上传文件的名称 String fileName = item.getName(); String ent = ""; //内容的类型 if (item.getContentType().equalsIgnoreCase("image/x-png") || item.getContentType().equalsIgnoreCase( "image/png")) { ent = ".png"; } else if (item.getContentType().equalsIgnoreCase( "image/gif")) { ent = ".gif"; } else if (item.getContentType().equalsIgnoreCase( "image/bmp")) { ent = ".bmp"; } else if (item.getContentType().equalsIgnoreCase( "image/pjpeg") || item.getContentType().equalsIgnoreCase( "image/jpeg")) { ent = ".jpg"; } //获取文件的是那种格式 if (fileName.lastIndexOf(".") != -1) { ent = fileName.substring(fileName.lastIndexOf(".")); } fileName = "ev_" + System.currentTimeMillis() + ent; // 定义文件路径,根据你的文件夹结构,可能需要做修改 if (t.equals("1")) { path = "upload/ev/" + fileName; } else { path = "upload/pk/" + fileName; } // 保存文件到服务器上 File file = new File(req.getSession().getServletContext() .getRealPath(path)); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } item.write(file); // logger.info(path); // break; ob.accumulate("url", path); } } resp.setContentType("text/html; charset=UTF-8"); resp.getWriter().write(ob.toString()); } catch (Exception e) { e.printStackTrace(); } finally { // 响应客户端 // resp.setContentType("text/html; charset=UTF-8"); // resp.getWriter().write(ob.toString()); } } }