本文實例為大家分享了文件上傳下載java實現代碼,供大家參考,具體內容如下
前臺:
1. 提交方式:post
2. 表單中有文件上傳的表單項: <input type=”file” />
3. 指定表單類型:
默認類型:enctype="application/x-www-form-urlencoded"
文件上傳類型:multipart/form-data
FileUpload
文件上傳功能開發中比較常用,apache也提供了文件上傳組件!
FileUpload組件:
1. 下載源碼
2. 項目中引入jar文件
commons-fileupload-1.2.1.jar 【文件上傳組件核心jar包】
commons-io-1.4.jar 【封裝了對文件處理的相關工具類】
使用:
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
|
public class UploadServlet extends HttpServlet { // upload目錄,保存上傳的資源 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*********文件上傳組件: 處理文件上傳************/ try { // 1. 文件上傳工廠 FileItemFactory factory = new DiskFileItemFactory(); // 2. 創建文件上傳核心工具類 ServletFileUpload upload = new ServletFileUpload(factory); // 一、設置單個文件允許的最大的大小: 30M upload.setFileSizeMax( 30 * 1024 * 1024 ); // 二、設置文件上傳表單允許的總大小: 80M upload.setSizeMax( 80 * 1024 * 1024 ); // 三、 設置上傳表單文件名的編碼 // 相當于:request.setCharacterEncoding("UTF-8"); upload.setHeaderEncoding( "UTF-8" ); // 3. 判斷: 當前表單是否為文件上傳表單 if (upload.isMultipartContent(request)){ // 4. 把請求數據轉換為一個個FileItem對象,再用集合封裝 List<FileItem> list = upload.parseRequest(request); // 遍歷: 得到每一個上傳的數據 for (FileItem item: list){ // 判斷:普通文本數據 if (item.isFormField()){ // 普通文本數據 String fieldName = item.getFieldName(); // 表單元素名稱 String content = item.getString(); // 表單元素名稱, 對應的數據 //item.getString("UTF-8"); 指定編碼 System.out.println(fieldName + " " + content); } // 上傳文件(文件流) ----> 上傳到upload目錄下 else { // 普通文本數據 String fieldName = item.getFieldName(); // 表單元素名稱 String name = item.getName(); // 文件名 String content = item.getString(); // 表單元素名稱, 對應的數據 String type = item.getContentType(); // 文件類型 InputStream in = item.getInputStream(); // 上傳文件流 /* * 四、文件名重名 * 對于不同用戶readme.txt文件,不希望覆蓋! * 后臺處理: 給用戶添加一個唯一標記! */ // a. 隨機生成一個唯一標記 String id = UUID.randomUUID().toString(); // b. 與文件名拼接 name = id +"#"+ name; // 獲取上傳基路徑 String path = getServletContext().getRealPath("/upload"); // 創建目標文件 File file = new File(path,name); // 工具類,文件上傳 item.write(file); item.delete(); //刪除系統產生的臨時文件 System.out.println(); } } } else { System.out.println("當前表單不是文件上傳表單,處理失敗!"); } } catch (Exception e) { e.printStackTrace(); } } // 手動實現過程 private void upload(HttpServletRequest request) throws IOException, UnsupportedEncodingException { /* request.getParameter(""); // GET/POST request.getQueryString(); // 獲取GET提交的數據 request.getInputStream(); // 獲取post提交的數據 */ /***********手動獲取文件上傳表單數據************/ //1. 獲取表單數據流 InputStream in = request.getInputStream(); //2. 轉換流 InputStreamReader inStream = new InputStreamReader(in, "UTF-8" ); //3. 緩沖流 BufferedReader reader = new BufferedReader(inStream); // 輸出數據 String str = null ; while ((str = reader.readLine()) != null ) { System.out.println(str); } // 關閉 reader.close(); inStream.close(); in.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this .doGet(request, response); } } |
案例:
Index.jsp
1
2
3
4
5
|
< body > < a href = "${pageContext.request.contextPath }/upload.jsp" >文件上傳</ a > < a href = "${pageContext.request.contextPath }/fileServlet?method=downList" >文件下載</ a > </ body > |
Upload.jsp
1
2
3
4
5
6
7
8
9
10
|
< body > < form name = "frm_test" action = "${pageContext.request.contextPath }/fileServlet?method=upload" method = "post" enctype = "multipart/form-data" > <%--< input type = "hidden" name = "method" value = "upload" >--%> 用戶名:< input type = "text" name = "userName" > < br /> 文件: < input type = "file" name = "file_img" > < br /> < input type = "submit" value = "提交" > </ form > </ body > |
FileServlet.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
|
/** * 處理文件上傳與下載 * @author Jie.Yuan * */ public class FileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲取請求參數: 區分不同的操作類型 String method = request.getParameter( "method" ); if ( "upload" .equals(method)) { // 上傳 upload(request,response); } else if ( "downList" .equals(method)) { // 進入下載列表 downList(request,response); } else if ( "down" .equals(method)) { // 下載 down(request,response); } } /** * 1. 上傳 */ private void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // 1. 創建工廠對象 FileItemFactory factory = new DiskFileItemFactory(); // 2. 文件上傳核心工具類 ServletFileUpload upload = new ServletFileUpload(factory); // 設置大小限制參數 upload.setFileSizeMax( 10 * 1024 * 1024 ); // 單個文件大小限制 upload.setSizeMax( 50 * 1024 * 1024 ); // 總文件大小限制 upload.setHeaderEncoding( "UTF-8" ); // 對中文文件編碼處理 // 判斷 if (upload.isMultipartContent(request)) { // 3. 把請求數據轉換為list集合 List<FileItem> list = upload.parseRequest(request); // 遍歷 for (FileItem item : list){ // 判斷:普通文本數據 if (item.isFormField()){ // 獲取名稱 String name = item.getFieldName(); // 獲取值 String value = item.getString(); System.out.println(value); } // 文件表單項 else { /******** 文件上傳 ***********/ // a. 獲取文件名稱 String name = item.getName(); // ----處理上傳文件名重名問題---- // a1. 先得到唯一標記 String id = UUID.randomUUID().toString(); // a2. 拼接文件名 name = id + "#" + name; // b. 得到上傳目錄 String basePath = getServletContext().getRealPath( "/upload" ); // c. 創建要上傳的文件對象 File file = new File(basePath,name); // d. 上傳 item.write(file); item.delete(); // 刪除組件運行時產生的臨時文件 } } } } catch (Exception e) { e.printStackTrace(); } } /** * 2. 進入下載列表 */ private void downList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 實現思路:先獲取upload目錄下所有文件的文件名,再保存;跳轉到down.jsp列表展示 //1. 初始化map集合Map<包含唯一標記的文件名, 簡短文件名> ; Map<String,String> fileNames = new HashMap<String,String>(); //2. 獲取上傳目錄,及其下所有的文件的文件名 String bathPath = getServletContext().getRealPath( "/upload" ); // 目錄 File file = new File(bathPath); // 目錄下,所有文件名 String list[] = file.list(); // 遍歷,封裝 if (list != null && list.length > 0 ){ for ( int i= 0 ; i<list.length; i++){ // 全名 String fileName = list[i]; // 短名 String shortName = fileName.substring(fileName.lastIndexOf( "#" )+ 1 ); // 封裝 fileNames.put(fileName, shortName); } } // 3. 保存到request域 request.setAttribute( "fileNames" , fileNames); // 4. 轉發 request.getRequestDispatcher( "/downlist.jsp" ).forward(request, response); } /** * 3. 處理下載 */ private void down(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲取用戶下載的文件名稱(url地址后追加數據,get) String fileName = request.getParameter( "fileName" ); fileName = new String(fileName.getBytes( "ISO8859-1" ), "UTF-8" ); // 先獲取上傳目錄路徑 String basePath = getServletContext().getRealPath( "/upload" ); // 獲取一個文件流 InputStream in = new FileInputStream( new File(basePath,fileName)); // 如果文件名是中文,需要進行url編碼 fileName = URLEncoder.encode(fileName, "UTF-8" ); // 設置下載的響應頭 response.setHeader( "content-disposition" , "attachment;fileName=" + fileName); // 獲取response字節流 OutputStream out = response.getOutputStream(); byte [] b = new byte [ 1024 ]; int len = - 1 ; while ((len = in.read(b)) != - 1 ){ out.write(b, 0 , len); } // 關閉 out.close(); in.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this .doGet(request, response); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助。