FileUpload是Apache組織提供的免費上傳元件,可以直接從Apache站點上下載下傳 :
1.commmons-fileupload:
http://commons.apache.org/proper/commons-fileupload/
2.commons-io:
http://commons.apache.org/proper/commons-io/
以後的講解,改用MyEclipse,這樣可以友善地講解Web項目。
一.導入commmons-fileupload和commons-io
建立一個Web Project後然後,選擇到WEB-INF右擊建立一個普通檔案夾--“lib”。這個
用于存放第三方開發包,再将這兩個包複制到lib中,然後分别對兩個包進行右鍵-->Build
Path後即完成了導入,導入後有如下效果:
lib包的圖示左下角會多一個圖示,然後Referenced Libraries 會出現兩個包,這就表示導入成功了。
二.FileUpload接受上傳内容
表單html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>fileload.html</title>
</head>
<body>
<form action="fileupload.jsp" method="post"
enctype="multipart/form-data">
<input type="file" name="pic"><br>
<input type="submit" value="上傳">
<input type="reset" value="重置">
</form>
</body>
</html>
接受jsp:
<%@ page contentType="text/html" language="java" pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%
//建立磁盤工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
//建立處理工具
//如果ServletFileUpload執行個體中不設定上面的Factory則報
//java.lang.NullPointerException: No FileItemFactory has been set.
ServletFileUpload upload = new ServletFileUpload(factory);
//設定上傳大小 3*1024*1024 = 3MB 這裡的機關是B
upload.setFileSizeMax(3145728);
//接受全部内容
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
//取出每個上傳檔案
FileItem item = iter.next();
//得到表單控件的名稱
String fieldName = item.getFieldName();
%>
<%
//如果不是普通文本資料,是上傳檔案
if (!item.isFormField()) {
//得到檔案名
String fileName = item.getName();
//得到檔案類型
String contentType = item.getContentType();
//得到長度
long fileSize = item.getSize();
%>
<li>檔案名:<%=fileName%>
<li>檔案類型:<%=contentType%>
<li>檔案長度:<%=fileSize%> <%
} else {
//取得表單内容
String value = item.getString();
%>
<li>普通參數:<%=value%> <%
}
}
%>
</ul>
</body>
</html>
三.儲存多個上傳檔案
表單html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>fileload.html</title>
</head>
<body>
<form action="fileupload_2.jsp" method="post"
enctype="multipart/form-data">
照片_1:<input type="file" name="pic_1"><br>
照片_2:<input type="file" name="pic_2"><br>
照片_3:<input type="file" name="pic_3"><br>
<input type="submit" value="上傳">
<input type="reset" value="重置">
</form>
</body>
</html>
這裡我們需要對儲存的檔案命名,所有引入了一個處理類:IPTimeStamp:
package com.zyy.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class IPTimeStamp {
private SimpleDateFormat sdf = null;
private String ip = null;
public IPTimeStamp() {
}
public IPTimeStamp(String ip) {
this.ip = ip;
}
public String getIPTimeRand() {
StringBuffer buf = new StringBuffer();
if (this.ip != null) {
String s[] = this.ip.split("\\.");
for (int i = 0; i < s.length; i++) {
buf.append(this.addZero(s[i], 3));
}
}
buf.append(this.getTimeStamp());
Random r = new Random();
for (int i = 0; i < 3; i++) {
buf.append(r.nextInt(10));
}
return buf.toString();
}
public String getDate() {
this.sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
return this.sdf.format(new Date());
}
public String getTimeStamp() {
this.sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return this.sdf.format(new Date());
}
private String addZero(String str, int len) {
StringBuffer s = new StringBuffer();
s.append(str);
while (s.length() < len) {
s.insert(0, "0");
}
return s.toString();
}
public static void main(String args[]) {
System.out.println(new IPTimeStamp("192.168.1.1").getIPTimeRand());
}
}
儲存jsp:
<%@ page contentType="text/html" language="java" pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="com.zyy.util.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%
//建立磁盤工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
//設定臨時檔案夾
File fileTemp = new File(this.getServletContext().getRealPath("/")
+ "uploadtemp");
if (!fileTemp.exists()) {
fileTemp.mkdir();
}
factory.setRepository(fileTemp);
//存放圖檔的檔案夾
File file = new File(this.getServletContext().getRealPath("/")
+ "upload");
if (!file.exists()) {
file.mkdir();
}
//建立處理工具
ServletFileUpload upload = new ServletFileUpload();
//設定上傳大小 3*1024*1024 = 3MB 這裡的機關是B
upload.setFileSizeMax(3145728);
upload.setFileItemFactory(factory);
//接受全部内容
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
//通路的時候 用127.0.0.1通路 如果用localhost通路的話 是IPV6 不是IPV4
IPTimeStamp ipts = new IPTimeStamp(request.getRemoteAddr());
while (iter.hasNext()) {
//取出每個上傳檔案
FileItem item = iter.next();
//得到表單控件的名稱
String fieldName = item.getFieldName();
%>
<%
//如果不是普通文本資料,是上傳檔案
if (!item.isFormField()) {
File saveFile = null;
InputStream input = null;
OutputStream output = null;
input = item.getInputStream();
output = new FileOutputStream(new File(this
.getServletContext().getRealPath("/")
+ "upload"
+ File.separator
+ ipts.getIPTimeRand()
+ "."
+ item.getName().split("\\.")[1]
));
byte data[] = new byte[1024];
int temp = 0;
while ((temp = input.read(data, 0, 1024)) != -1) {
output.write(data);
}
input.close();
output.close();
%>
<%
} else {
//取得表單内容
String value = item.getString();
%>
<li>普通參數:<%=value%> <%
}
}
%>
</ul>
</body>
</html>
成功後,由于儲存在的是this.getServletContext().getRealPath("/"),這是虛
拟目錄的根目錄,由于這是MyEclipse啟動的是非MyEclipse自帶的Tomcat。是以我們找
到Tomcat目錄/webapps/項目,可以看到