一、Servlet實現(xiàn)文件上傳,需要添加第三方提供的jar包
下載地址:
1) commons-fileupload-1.2.2-bin.zip : 點擊打開鏈接
2) commons-io-2.3-bin.zip : 點擊打開鏈接
接著把這兩個jar包放到 lib文件夾下:
二、文件上傳的表單提交方式必須是POST方式
編碼類型:enctype="multipart/form-data",默認是 application/x-www-form-urlencoded
比如:<form action="FileUpLoad"enctype="multipart/form-data"method="post">
三、舉例
1.fileupload.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
|
<%@ 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%>" rel="external nofollow" rel="external nofollow" > < title >My JSP 'fileupload.jsp' starting page</ 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" > <!-- <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" > --> </ head > < body > <!-- enctype 默認是 application/x-www-form-urlencoded --> < form action = "FileUpLoad" enctype = "multipart/form-data" method = "post" > 用戶名:< input type = "text" name = "usename" > < br /> 上傳文件:< input type = "file" name = "file1" >< br /> 上傳文件: < input type = "file" name = "file2" >< br /> < input type = "submit" value = "提交" /> </ form > </ body > </ html > |
2.實際處理文件上傳的 FileUpLoad.java
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
|
package com.servlet.fileupload; import java.io.File; import java.io.*; 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 org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * * @author Administrator * 文件上傳 * 具體步驟: * 1)獲得磁盤文件條目工廠 DiskFileItemFactory 要導包 * 2) 利用 request 獲取 真實路徑 ,供臨時文件存儲,和 最終文件存儲 ,這兩個存儲位置可不同,也可相同 * 3)對 DiskFileItemFactory 對象設置一些 屬性 * 4)高水平的API文件上傳處理 ServletFileUpload upload = new ServletFileUpload(factory); * 目的是調用 parseRequest(request)方法 獲得 FileItem 集合list , * * 5)在 FileItem 對象中 獲取信息, 遍歷, 判斷 表單提交過來的信息 是否是 普通文本信息 另做處理 * 6) * 第一種. 用第三方 提供的 item.write( new File(path,filename) ); 直接寫到磁盤上 * 第二種. 手動處理 * */ public class FileUpLoad extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding( "utf-8" ); //設置編碼 //獲得磁盤文件條目工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //獲取文件需要上傳到的路徑 String path = request.getRealPath( "/upload" ); //如果沒以下兩行設置的話,上傳大的 文件 會占用 很多內存, //設置暫時存放的 存儲室 , 這個存儲室,可以和 最終存儲文件 的目錄不同 /** * 原理 它是先存到 暫時存儲室,然后在真正寫到 對應目錄的硬盤上, * 按理來說 當上傳一個文件時,其實是上傳了兩份,第一個是以 .tem 格式的 * 然后再將其真正寫到 對應目錄的硬盤上 */ factory.setRepository( new File(path)); //設置 緩存的大小,當上傳文件的容量超過該緩存時,直接放到 暫時存儲室 factory.setSizeThreshold( 1024 * 1024 ) ; //高水平的API文件上傳處理 ServletFileUpload upload = new ServletFileUpload(factory); try { //可以上傳多個文件 List<FileItem> list = (List<FileItem>)upload.parseRequest(request); for (FileItem item : list) { //獲取表單的屬性名字 String name = item.getFieldName(); //如果獲取的 表單信息是普通的 文本 信息 if (item.isFormField()) { //獲取用戶具體輸入的字符串 ,名字起得挺好,因為表單提交過來的是 字符串類型的 String value = item.getString() ; request.setAttribute(name, value); } //對傳入的非 簡單的字符串進行處理 ,比如說二進制的 圖片,電影這些 else { /** * 以下三步,主要獲取 上傳文件的名字 */ //獲取路徑名 String value = item.getName() ; //索引到最后一個反斜杠 int start = value.lastIndexOf( "\" ); //截取 上傳文件的 字符串名字,加1是 去掉反斜杠, String filename = value.substring(start+ 1 ); request.setAttribute(name, filename); //真正寫到磁盤上 //它拋出的異常 用exception 捕捉 //item.write( new File(path,filename) );//第三方提供的 //手動寫的 OutputStream out = new FileOutputStream( new File(path,filename)); InputStream in = item.getInputStream() ; int length = 0 ; byte [] buf = new byte [ 1024 ] ; System.out.println( "獲取上傳文件的總共的容量:" +item.getSize()); // in.read(buf) 每次讀到的數(shù)據存放在 buf 數(shù)組中 while ( (length = in.read(buf) ) != - 1 ) { //在 buf 數(shù)組中 取出數(shù)據 寫到 (輸出流)磁盤上 out.write(buf, 0 , length); } in.close(); out.close(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); } request.getRequestDispatcher( "filedemo.jsp" ).forward(request, response); } } |
System.out.println("獲取上傳文件的總共的容量:"+item.getSize());
3.filedemo.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
|
<%@ 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%>" rel="external nofollow" rel="external nofollow" > < title >My JSP 'filedemo.jsp' starting page</ 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" > <!-- <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" > --> </ head > < body > 用戶名:${requestScope.usename } < br /> 文件:${requestScope.file1 }< br /> ${requestScope.file2 }< br /> <!-- 把上傳的圖片顯示出來 --> < img alt = "go" src = "upload/<%=(String)request.getAttribute(" file1")%> " /> </ body > </ html > |
4.結果頁面
下載鏈接:
1)Struts2之下載 點擊打開鏈接
2)Struts2之上傳 點擊打開鏈接
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。