一、文件上傳原理
1、文件上傳的前提:
a、form表單的method必須是post
b、form表單的enctype必須是multipart/form-data(決定了POST請求方式,請求正文的數據類型)
c、form中提供input的type是file類型的文件上傳域
二、利用第三方組件實現文件上傳
1、commons-fileupload組件:
jar:commons-fileupload.jar
commons-io.jar
2、核心類或接口
DiskFileItemFactory:設置環境
public void setSizeThreshold(int sizeThreshold) :設置緩沖區大小。默認是10Kb。
當上傳的文件超出了緩沖區大小,fileupload組件將使用臨時文件緩存上傳文件
public void setRepository(java.io.File repository):設置臨時文件的存放目錄。默認是系統的臨時文件存放目錄。
ServletFileUpload:核心上傳類(主要作用:解析請求的正文內容)
boolean isMultipartContent(HttpServletRequest?request):判斷用戶的表單的enctype是否是multipart/form-data類型的。
List parseRequest(HttpServletRequest request):解析請求正文中的內容
setFileSizeMax(4*1024*1024);//設置單個上傳文件的大小
upload.setSizeMax(6*1024*1024);//設置總文件大小
FileItem:代表表單中的一個輸入域。
boolean isFormField():是否是普通字段
String getFieldName:獲取普通字段的字段名
String getString():獲取普通字段的值
InputStream getInputStream():獲取上傳字段的輸入流
String getName():獲取上傳的文件名
實例:先在WEB-INF目錄下建一個files文件夾,也就是文件都要上傳到這里,也是避免其他人直接訪問
1.獲取files的真實路徑
String storePath = getServletContext().getRealPath("/WEB-INF/files");
2.設置環境
DiskFileItemFactory factory = new DiskFileItemFactory();//用默認的緩存和臨時文件存儲的地方
3.判斷表單傳送方式
1
2
3
4
5
6
|
boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { System.out.println( "上傳方式錯誤!" ); return ; } |
4.文件上傳核心類
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
|
ServletFileUpload upload = new ServletFileUpload(factory); 5 .解析 //解析 List<FileItem> items = upload.parseRequest(request); for (FileItem item: items) { if (item.isFormField()){ //普通字段,表單提交過來的 String fieldName = item.getFieldName(); //表單信息的字段名 String fieldValue = item.getString(); //表單信息字段值 System.out.println(fieldName+ "=" +fieldValue); } else //文件處理 { InputStream in = item.getInputStream(); //上傳文件名 C:\Users\Administrator\Desktop\a.txt String name = item.getName(); //只需要 a.txt String fileName = name.substring(name.lastIndexOf( "\\" )+ 1 ); //構建輸出流 String storeFile = storePath+ "\\" +fileName; //上傳文件的保存地址 OutputStream out = new FileOutputStream(storeFile); byte [] b = new byte [ 1024 ]; int len = - 1 ; while ((len=in.read(b))!=- 1 ) { out.write(b, 0 , len); } in.close(); //關閉流 out.close(); } } |
寫一個表單
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
|
<%@ 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 >My JSP '1.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"> --> </ head > < body > < form action = "${pageContext.request.contextPath}/servlet/UploadServlet2" method = "post" enctype = "multipart/form-data" > 用戶名< input type = "text" name = "username" /> < br /> < input type = "file" name = "f1" />< br /> < input type = "file" name = "f2" />< br /> < input type = "submit" value = "保存" /> </ form > </ body > </ html > |
寫一個提交servlet:UploadServlet2
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
|
package com.liuzhen.upload; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; 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; //文件上傳入門案例 public class UploadServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置編碼 request.setCharacterEncoding( "UTF-8" ); response.setContentType( "text/html;charset=UTF-8" ); try { //上傳文件的路徑 String storePath = getServletContext().getRealPath( "/WEB-INF/files" ); //設置環境 DiskFileItemFactory factory = new DiskFileItemFactory(); //判斷表單傳送方式 form enctype=multipart/form-data boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { System.out.println( "上傳方式錯誤!" ); return ; } ServletFileUpload upload = new ServletFileUpload(factory); //解析 List<FileItem> items = upload.parseRequest(request); for (FileItem item: items) { if (item.isFormField()){ //普通字段,表單提交過來的 String fieldName = item.getFieldName(); //表單信息的字段名 String fieldValue = item.getString(); //表單信息字段值 System.out.println(fieldName+ "=" +fieldValue); } else //文件處理 { InputStream in = item.getInputStream(); //上傳文件名 C:\Users\Administrator\Desktop\a.txt String name = item.getName(); //只需要 a.txt String fileName = name.substring(name.lastIndexOf( "\\" )+ 1 ); //構建輸出流 String storeFile = storePath+ "\\" +fileName; //上傳文件的保存地址 OutputStream out = new FileOutputStream(storeFile); byte [] b = new byte [ 1024 ]; int len = - 1 ; while ((len=in.read(b))!=- 1 ) { out.write(b, 0 , len); } in.close(); //關閉流 out.close(); } } } catch (FileUploadException e) { throw new RuntimeException(e); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } |
上傳的文件是在Tomcat應用中。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。