java组件commons-fileupload实现文件上传

一、所需要的包:
1、commons-fileupload-1.2.1.jar:
下载地址
http://commons.apache.org/downloads/download_fileupload.cgi
2、commons-io-1.4.jar:
下载地址
http://commons.apache.org/downloads/download_io.cgi

二、注意事项:
form表单里面要加上enctype="multipart/form-data" 

三、代码示例 

1、jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8" 
 pageEncoding="UTF-8"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>upload</title> 
</head> 
<body> 
<form action="uploadServlet" method="post" enctype="multipart/form-data"> 
 <table> 
 <caption>上传实例</caption> 
 <tr> 
  <td>姓名</td> 
  <td> 
  <input type="text" name="name"> 
  </td> 
 </tr> 
 <tr> 
  <td>年龄</td> 
  <td> 
  <input type="text" name="age"> 
  </td> 
 </tr> 
 <tr> 
  <td>照片</td> 
  <td> 
  <input type="file" name="image"> 
  </td> 
 </tr> 
 <tr> 
  <td></td> 
  <td> 
  <input type="submit" value="提交"> 
  </td> 
 </tr> 
 </table> 
</form> 
</body> 
</html> 

2、UploadServlet代码

package servlet; 
 
import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.Writer; 
import java.util.Iterator; 
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.FileUploadException; 
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import org.apache.commons.fileupload.util.Streams; 
 
/** 
 * 上传servlet 
 * @author lisanlai 
 * 
 */ 
public class UploadServlet extends HttpServlet { 
 private static final long serialVersionUID = 1L; 
  
 public UploadServlet() { 
 super(); 
 } 
 
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
 this.doPost(request, response); 
 } 
 
 @SuppressWarnings("unchecked") 
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
  
 response.setContentType("text/html"); 
 // 设置字符编码为UTF-8, 这样支持汉字显示 
 response.setCharacterEncoding("UTF-8"); 
 Writer o = response.getWriter(); 
  
 /** 
  * 首先判断form的enctype是不是multipart/form-data 
  * 同时也判断了form的提交方式是不是post 
  * 方法:isMultipartContent(request) 
  */ 
 
 if(ServletFileUpload.isMultipartContent(request)){ 
  request.setCharacterEncoding("utf-8"); 
  
  // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload 
  DiskFileItemFactory factory = new DiskFileItemFactory(); 
  
  //设置文件存放的临时文件夹,这个文件夹要真实存在 
  File fileDir = new File("../webapps/fileupload/tmp/"); 
  if(fileDir.isDirectory() && fileDir.exists()==false){ 
  fileDir.mkdir(); 
  } 
  factory.setRepository(fileDir); 
  
  //设置最大占用的内存 
  factory.setSizeThreshold(1024000); 
  
  //创建ServletFileUpload对象 
  ServletFileUpload sfu = new ServletFileUpload(factory); 
  sfu.setHeaderEncoding("utf-8"); 
  
  //设置单个文件最大值byte 
  sfu.setFileSizeMax(102400000); 
  
  //所有上传文件的总和最大值byte 
  sfu.setSizeMax(204800000); 
  
  List<FileItem> items = null; 
  
  try { 
  items = sfu.parseRequest(request); 
  }catch (SizeLimitExceededException e) { 
  System.out.println("文件大小超过了最大值"); 
  } catch(FileUploadException e) { 
  e.printStackTrace(); 
  } 
  
  //取得items的迭代器 
  Iterator<FileItem> iter = items==null?null:items.iterator(); 
  
  //图片上传后存放的路径目录 
  File images = new File("D:/upload/images/"); 
  if(images.exists()==false){ 
  images.mkdirs(); 
  } 
  //迭代items 
  while(iter!=null && iter.hasNext()){ 
  FileItem item = (FileItem) iter.next(); 
   
  //如果传过来的是普通的表单域 
  if(item.isFormField()){ 
   System.out.print("普通的表单域:"); 
   System.out.print(new String(item.getFieldName()) + " "); 
   System.out.println(new String(item.getString("UTF-8"))); 
  } 
  //文件域 
  else if(!item.isFormField()){ 
   System.out.println("源图片:" + item.getName()); 
   String fileName = item.getName().substring(item.getName().lastIndexOf("\\")); 
   BufferedInputStream in = new BufferedInputStream(item.getInputStream()); 
   //文件存储在D:/upload/images目录下,这个目录也得存在 
   BufferedOutputStream out = new BufferedOutputStream( 
    new FileOutputStream(new File(images.getAbsolutePath()+ fileName))); 
   Streams.copy(in, out, true); 
   o.write("文件上传成功"); 
  } 
  } 
 }else { 
  System.out.println("表单的enctype 类型错误"); 
 } 
 } 
 
} 

3、web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> 
 <display-name>UploadTest</display-name> 
 <welcome-file-list> 
 <welcome-file>upload.jsp</welcome-file> 
 </welcome-file-list> 
 <servlet> 
 <description></description> 
 <display-name>UploadServlet</display-name> 
 <servlet-name>UploadServlet</servlet-name> 
 <servlet-class>servlet.UploadServlet</servlet-class> 
 </servlet> 
 <servlet-mapping> 
 <servlet-name>UploadServlet</servlet-name> 
 <url-pattern>/uploadServlet</url-pattern> 
 </servlet-mapping> 
</web-app> 

本文已被整理到了《Java上传操作技巧汇总》,欢迎大家学习阅读。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。