javaweb-番外篇-Commons-FileUpload组件上传文件
一、Commons-FileUpload简介
Commons-FileUpload组件
Commons是Apache开放源代码组织的一个Java子项目,其中的FileUpload是用来处理HTTP文件上传的子项目
Commons-FileUpload组件特点
使用简单:可以方便地嵌入到JSP文件中,编写少量代码即可完成文件的上传功能 能够全程控制上传内容 能够对上传文件的大小、类型进行控制
获取Commons-FileUpload组件的方式
http://commons.apache.org/fileupload下载Commons-FileUpload组件
Commons-FileUpload组件类库:commons-fileupload-1.2.2.jar
Commons-FileUpload组件的API文档: apidocs
http://commons.apache.org/io下载Commons-IO组件 Commons-IO组件
类库:commons-io-2.4.jar
Commons-IO组件的API文档: commons-io-2.4\docs
二、Commons-FileUpload组件的API
三、Commons-FileUpload组件应用
四、代码
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>上传</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <form action="DoUpLoadServlet" enctype="multipart/form-data" method="post"> <p>选择图片:<input type="file" name="nfile"></p> <p><input type="submit" value="提交"></p> </form> </body> </html>
DoUpLoadServlet
package com.qj.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; 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.FileUploadBase; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Servlet implementation class DoUpLoadServlet */ @WebServlet("/DoUpLoadServlet") public class DoUpLoadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DoUpLoadServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String uploadFileName = ""; //上传的文件名 String fieldName = ""; //表单字段元素的name属性值 PrintWriter out = response.getWriter();//获取out对象 //请求信息中的内容是否是multipart类型 boolean isMultipart = ServletFileUpload.isMultipartContent(request); //上传文件的存储路径(服务器文件系统上的绝对文件路径) String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/" ); //创建临时文件目录路径 File tempPatchFile=new File("d:\\temp\\buffer\\"); if(!tempPatchFile.exists()) //判断文件或目录是否存在 tempPatchFile.mkdirs(); //创建指定的目录,包括所有必需但不存在的父目录 if (isMultipart) { DiskFileItemFactory factory=new DiskFileItemFactory(); //设置缓冲区大小4kb factory.setSizeThreshold(4096); //设置上传文件用到临时文件存放路径 factory.setRepository(tempPatchFile); ServletFileUpload upload = new ServletFileUpload(factory); //设置单个文件的最大限制 upload.setSizeMax(1024*30); try { //解析form表单中所有文件 List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { //依次处理每个文件 FileItem item = (FileItem) iter.next(); if (!item.isFormField()){ //文件表单字段 String fileName = item.getName(); //通过Arrays类的asList()方法创建固定长度的集合 List<String> filType=Arrays.asList("gif","bmp","jpg"); String ext=fileName.substring(fileName.lastIndexOf(".")+1); if(!filType.contains(ext)) //判断文件类型是否在允许范围内 out.print("上传失败,文件类型只能是gif、bmp、jpg"); else{ if (fileName != null && !fileName.equals("")) { File fullFile = new File(item.getName()); File saveFile = new File(uploadFilePath, fullFile.getName()); item.write(saveFile); uploadFileName = fullFile.getName(); out.print("上传成功后的文件名是:"+uploadFileName+ ",文件大小是:"+item.getSize()+"bytes!"); } } } } }catch(FileUploadBase.SizeLimitExceededException ex){ out.print("上传失败,文件太大,单个文件的最大限制是:"+upload.getSizeMax()+"bytes!"); }catch (Exception e) { e.printStackTrace(); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }