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/项目,可以看到