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

时间:2021-07-09 18:21:49

一、所需要的包:
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代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<%@ 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代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

相关文章