1.1 文件上傳概述
- 文件上傳
- 用戶將本地文件通過(guò)網(wǎng)絡(luò)上傳至服務(wù)器的過(guò)程
- 應(yīng)用場(chǎng)景
- 相親網(wǎng)站的照片上傳
- 招聘網(wǎng)站的簡(jiǎn)歷上傳
- 文件上傳的技術(shù)
名稱 |
描述 |
jspSmartUpload |
應(yīng)用在jsp上的文件上傳和文件下載的組件 |
fileupload |
應(yīng)用在java上的文件上傳技術(shù)干发,由Apache開(kāi)源組織提供 |
servlet3.0 |
提供了文件上傳的技術(shù) |
Struts |
提供了文件上傳的技術(shù) |
- 文件上傳的條件
- 需要有一個(gè)表單
- 表單的method屬性的值必須設(shè)置為post
- 表單的enctype屬性的值需要設(shè)置為multipart/form-data
- 表單需要有一個(gè)input標(biāo)簽
- input標(biāo)簽type屬性的值需要設(shè)置為file
- input標(biāo)簽需要有name屬性和值
1.2 JSP編寫(xiě)
- 一些屬性的注釋
- enctype:encode type 編碼類型:屬性規(guī)定了發(fā)送服務(wù)器之前如何對(duì)表單數(shù)據(jù)進(jìn)行編碼
- application/x-www-form-urlencoded %WE%RT 默認(rèn)對(duì)表單數(shù)據(jù)進(jìn)行url編碼,不能用于文件上傳
- multipart/form-data:表單數(shù)據(jù)有多個(gè)部分組成:既有文本數(shù)據(jù),還有文件,圖片這些二進(jìn)制數(shù)據(jù)設(shè)置之后,瀏覽器會(huì)將文件以二進(jìn)制的方式上傳,可以實(shí)現(xiàn)多種類型的文
件上傳
<%@ 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>Insert title here</title>
</head>
<body>
<h1>文件上傳</h1>
<form action="${pageContext.request.contextPath}/UploadServlet" method="post" enctype="multipart/form-data">
文件信息:<input type="text" name="info"/>
<br />
用戶名:<input type="text" name="username"/>
<br />
文件:<input type="file" name="file01" />
<br />
文件2:<input type="file" name="file02" />
<br />
<input type="submit" value="上傳"/>
</form>
</body>
</html>
1.3 Servlet的編寫(xiě)
- 編寫(xiě)流程
- 創(chuàng)建一個(gè)磁盤(pán)文件的工廠對(duì)象
- 創(chuàng)建文件上傳的核心對(duì)象
- 通過(guò)核心對(duì)象解析請(qǐng)求對(duì)象得到一個(gè)集合對(duì)象,他里面包含所有的表單項(xiàng)對(duì)象
- 遍歷這個(gè)集合對(duì)象,得到每一個(gè)表單項(xiàng),判斷他是否是普通表單項(xiàng)
- 如果是普通的表單項(xiàng),獲取他的name和value的值
- 如果不是,創(chuàng)建IO流傳輸
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//獲取表單所提交的數(shù)據(jù)
//創(chuàng)建磁盤(pán)文件的工廠對(duì)象
DiskFileItemFactory dfif = new DiskFileItemFactory();
//創(chuàng)建文件上傳的核心對(duì)象
ServletFileUpload upload = new ServletFileUpload(dfif);
//解析請(qǐng)求對(duì)象臊旭,獲取表單所提交的數(shù)據(jù)
List<FileItem> items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//遍歷集合對(duì)象
if(items != null) {
for (FileItem fileItem : items) {
//判斷表單項(xiàng)是否是普通的表單項(xiàng)
if(fileItem.isFormField()) {
//確定是普通的表單項(xiàng)
//獲取普通表單項(xiàng)name屬性的值
String fieldName = fileItem.getFieldName();
//獲取普通表單項(xiàng)value屬性的值
String fieldValue = fileItem.getString("UTF-8");
System.out.println(fieldName + "=" + fieldValue);
}
else {
//文件上傳的表單項(xiàng)
//獲取文件名稱
String fileName = fileItem.getName();
//獲取文件的內(nèi)容
InputStream is = fileItem.getInputStream();
/*byte[] bys = new byte[1024];
int len = 0;
while((len = is.read(bys)) != -1) {
System.out.println(new String(bys,0,len));
}*/
String realPath = getServletContext().getRealPath("/file");
File file = new File(realPath);
if(!file.exists()) {
//目錄不存在,則要?jiǎng)?chuàng)建
file.mkdirs();
}
//創(chuàng)建輸出流對(duì)象
OutputStream os = new FileOutputStream(realPath + "/" + fileName);
byte[] bys = new byte[1024];
int len = 0;
while((len = is.read(bys)) != -1) {
os.write(bys, 0, len);
}
os.close();
}
}
}
}
1.4 DiskFileItemFactory的常用API
方法 |
描述 |
void setSizeThreshold(int sizeThreshold) |
設(shè)置緩沖區(qū)大小 |
void setRepository(java.io.File repository) |
設(shè)置臨時(shí)目錄 |
DiskFileItemFactory dfif = new DiskFileItemFactory();
// 設(shè)置緩沖區(qū)大小
dfif.setSizeThreshold(1024 * 1024 * 6);// 6M
// 設(shè)置臨時(shí)目錄
String tempPath = getServletContext().getRealPath("/temp");
File temp = new File(tempPath);
if (!temp.exists()) {
temp.mkdirs();
}
dfif.setRepository(temp);
- 注意:
- 如果上傳的文件不是很大,先走緩沖區(qū)
- 如果上傳文件比較大,超過(guò)緩沖區(qū)的大小,就不走緩沖區(qū)了,他會(huì)把文件先上傳到臨時(shí)目錄中,再把臨時(shí)目錄中的臨時(shí)文件復(fù)制到file目錄中
- 需要把整個(gè)文件上傳工作完成之后才把臨時(shí)文件復(fù)制到我們指定的File目錄中
- 需要先把Tomcat關(guān)掉才能手動(dòng)刪掉temp里面的文件
- 臨時(shí)文件臨時(shí)目錄的作用 是做一些續(xù)傳的操作
1.5 ServletFileUpload的常用API
方法 |
描述 |
static boolean isMultipartContent(javax.servlet.http.HttpServletRequest request) |
用來(lái)判斷表單 link-tap的屬性值是否是mutipart 是返回ture 否則返回 false |
public void setFileSizeMax(long fileSizeMax) |
設(shè)置一個(gè)請(qǐng)求中單個(gè)文件的大小 |
public void setSizeMax(long sizeMax) |
設(shè)置一個(gè)請(qǐng)求中所有文件的總大小 |
boolean flag = ServletFileUpload.isMultipartContent(request);
if (!flag) {
request.setAttribute("msg", "表單提交數(shù)據(jù)的方式錯(cuò)誤晌缘!");
request.getRequestDispatcher("/upload.jsp").forward(request,
response);
return;
}
ServletFileUpload upload = new ServletFileUpload(dfif);
// 設(shè)置文件的大小
upload.setFileSizeMax(1024 * 1024 * 40);//40M
// 設(shè)置請(qǐng)求中所有文件的總大小
upload.setSizeMax(1024 * 1024 * 40);//40M
- 注意:
- 工廠對(duì)象既可以通過(guò)構(gòu)造方法傳遞,也可以通過(guò)他所對(duì)應(yīng)的set方法傳遞
1.7 FileItem的常用API
方法 |
描述 |
long getSize() |
獲取表單上傳文件的大小 |
void delete() |
刪除臨時(shí)文件 |
void write(java.io.File file) |
直接寫(xiě)一個(gè)文件 |
1.8 上傳Servlet 改寫(xiě)
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 判斷表單提交數(shù)據(jù)的方式是否正確
boolean flag = ServletFileUpload.isMultipartContent(request);
if (!flag) {
request.setAttribute("msg", "表單提交數(shù)據(jù)的方式錯(cuò)誤饰豺!");
request.getRequestDispatcher("/upload.jsp").forward(request,
response);
return;
}
// 實(shí)現(xiàn)文件上傳的功能
DiskFileItemFactory dfif = new DiskFileItemFactory();
// 設(shè)置緩沖區(qū)大小
dfif.setSizeThreshold(1024 * 1024 * 6);// 6M
// 設(shè)置臨時(shí)目錄
String tempPath = getServletContext().getRealPath("/temp");
File temp = new File(tempPath);
if (!temp.exists()) {
temp.mkdirs();
}
dfif.setRepository(temp);
ServletFileUpload upload = new ServletFileUpload(dfif);
// 設(shè)置文件的大小
// upload.setFileSizeMax(1024 * 1024 * 40);//40M
// 設(shè)置請(qǐng)求中所有文件的總大小
// upload.setSizeMax(1024 * 1024 * 40);//40M
List<FileItem> items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (items != null) {
for (FileItem fileItem : items) {
if (fileItem.isFormField()) {
String fieldName = fileItem.getFieldName();
String fieldValue = fileItem.getString("UTF-8");
System.out.println(fieldName + "=" + fieldValue);
} else {
//獲取表單上傳文件的大小
long size = fileItem.getSize();
if(size > 0) {
String fileName = fileItem.getName();
/*InputStream is = fileItem.getInputStream();
String realPath = getServletContext().getRealPath("/file");
File file = new File(realPath);
if (!file.exists()) {
file.mkdirs();
}
OutputStream os = new FileOutputStream(realPath + "/" + fileName);
byte[] bys = new byte[1024];
int len = 0;
while ((len = is.read(bys)) != -1) {
os.write(bys, 0, len);
}
//關(guān)閉輸入流亿鲜,刪除臨時(shí)文件需要
is.close();
os.close();*/
String realPath = getServletContext().getRealPath("/file");
File file = new File(realPath);
if (!file.exists()) {
file.mkdirs();
}
//File uploadFile = new File(file,fileName);
try {
fileItem.write(new File(file,fileName));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//刪除臨時(shí)文件
fileItem.delete();
}
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者