fileUpload上传:
第一步,配置开发包
将fileupload包中的jar文件拷贝到tomcat安装包下的lib文件夹中
将commance下io包中的jar文件拷贝到tomcat安装包下的lib文件夹中
第二步,在FileUpload之中,不管是基本数据还是上传的文件,只要是上传了,
则一切的操作都是按照FileItem表示出来,都通过List一起接收。
创建磁盘工厂:
DiskFileItemFactory factory= new DiskFileItemFactory();
创建处理工具:
ServletFileUpload upload = new ServletFileUpload(factory);
设置上传文件大小:
第一步,配置开发包
将fileupload包中的jar文件拷贝到tomcat安装包下的lib文件夹中
将commance下io包中的jar文件拷贝到tomcat安装包下的lib文件夹中
第二步,在FileUpload之中,不管是基本数据还是上传的文件,只要是上传了,
则一切的操作都是按照FileItem表示出来,都通过List一起接收。
创建磁盘工厂:
DiskFileItemFactory factory= new DiskFileItemFactory();
创建处理工具:
ServletFileUpload upload = new ServletFileUpload(factory);
设置上传文件大小:
upload.setFileSizeMax(3145728);
接收全部内容:List<FileItem>items = upload.parseRequest(request);
下面给出一个测试例子:
fileupload.html:
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="fileupload.jsp" method="post"
enctype="multipart/form-data" >
姓名:<input type="text" name="uname"><br>
照片:<input type="file" name="pic"><br>
照片:<input type="file" name="pic"><br>
照片:<input type="file" name="pic"><br>
<input type="submit" value="上传">
<input type="reset" value="重置">
</form>
</body>
</html>
fileupload.jsp:
<%@page contentType="text/html" pageEncoding="gbk" %>
<%@page import="java.util.*,java.io.*" %>
<%@page import ="org.apache.commons.fileupload.*" %>
<%@page import ="org.apache.commons.fileupload.disk.*" %>
<%@page import ="org.apache.commons.fileupload.servlet.*" %>
<%@page import ="webstudy.*" %>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%
DiskFileItemFactory factory= new DiskFileItemFactory();
factory.setRepository(new
File(this.getServletContext().getRealPath("/")+"uploadtemp"));
//保存临时文件
ServletFileUpload upload= new ServletFileUpload(factory);
upload.setFileSizeMax(3*1024*1024);//是只能上传3兆大小
List<FileItem> items = upload.parseRequest(request);//接收全部内容
Iterator<FileItem>iter =items.iterator();
IpTimeStamp its = new IpTimeStamp("163.123.23.54");
while(iter.hasNext()){
FileItem item =iter.next();
String fileName = item.getFieldName();//取得表单控件的内容
%>
<ul><h4><%=fileName%></h4>
<%
if(!item.isFormField()){ //不是普通文本
String filename=item.getName();//取得文件名称
String contentType=item.getContentType();//取得文本类型
long sizeInBytes = item.getSize();
File saveFile = null;
InputStream input = null;
OutputStream output =null;
input = item.getInputStream();
output= new FileOutputStream(
new File(this.getServletContext().getRealPath("/")+"upload")
+File.separator+its.getIpTimeRand()+"."+item.getName().split("\\.")[1]);
int temp =0;
byte data[] =new byte[512];
while((temp=input.read(data,0,512))!=-1){
output.write(data);
}
input.close();
output.close();
%>
<li>上传文件名称:<%=filename%>
<li>上传文件类型:<%=contentType%>
<li>上传文件大小:<%=sizeInBytes%>
<%
}else{
String value=item.getString();
%>
<li>普通参数:<%=value%>
<%
}
%>
</ul>
<%
}
%>
</body>
</html>
现在我们可以清楚地发现这种方法的复杂性。并且,
Fileupload也有许多的问题。
1无法像request.getParmeter()方法那样准确的取得提交的参数;
2 无法像request.getParmeterValues()那样准确的取得一组提交参数
3 所有的上传文件都需要进行依次的判断,才能够分别保存
,不能批量保存。
因此,为了方便使用,故将其封装成一个类。
package fileupload;
import java.util.*;
import java.io.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;
import fileupload.*;
public class fileuploadTools {
private HttpServletRequest request = null;
private List<FileItem> items = null;
private Map<String,List<String>> params = new HashMap<String,List<String>>();
private Map<String,FileItem> files = new HashMap<String,FileItem>();
public fileuploadTools(HttpServletRequest request,int maxSize,String tempDir) throws Exception {
this.request=request;
DiskFileItemFactory factory= new DiskFileItemFactory();
if(tempDir!=null)
factory.setRepository(new File(tempDir));
ServletFileUpload upload = new ServletFileUpload(factory);
if(maxSize>0){
upload.setFileSizeMax(maxSize);
}
this.items=upload.parseRequest(request);
this.init();
}
private void init(){
Iterator<FileItem> iter = this.items.iterator();
IpTimeStamp its = new IpTimeStamp(this.request.getRemoteAddr());
// IpTimeStamp its = new IpTimeStamp("164.234.12.32");
while(iter.hasNext()){
FileItem item =iter.next();
if(item.isFormField()){ //普通参数
String name= item.getFieldName();
String value=item.getString();
List<String>temp = null;
if(this.params.containsKey(name)){
temp = this.params.get(name);
}
else{
temp = new ArrayList<String>();
}
temp.add(value);
this.params.put(name, temp);
} else{ //按照文件
String fileName = its.getIpTimeRand()+"."+item.getName().split("\\.")[1];
this.files.put(fileName,item);
}
}
}
public String getParameter(String name){
//根据参数取出内容
String ret = null;
List<String> temp = this.params.get(name);
if(temp!=null){
ret=temp.get(0);
}
return ret;
}
public String[] getParmeterValues(String name){
String ret[] = null;
List<String> temp = this.params.get(name);
if(temp!=null){
ret = temp.toArray(new String[]{});
}
return ret;
}
public Map<String,FileItem> getUploadFiles(){
return this.files;
}
//保存之后一定要有名字
public List<String> saveAll(String saveDir) throws IOException{
List<String> names = new ArrayList<String>();
if(this.files.size()>0){
//有内容
Set<String>keys = this.files.keySet();//key是文件的名称
Iterator<String> iter = keys.iterator();
File saveFile= null;
InputStream input = null;
OutputStream output = null;
while(iter.hasNext()){
FileItem item = this.files.get(iter.next());
String fileName = new IpTimeStamp(request.getRemoteAddr()).getIpTimeRand()+"."+item.getName().split("\\.")[1];
saveFile = new File(saveDir+fileName);
names.add(fileName); //名字不返回后期无法操作
try{
input = item.getInputStream();
output = new FileOutputStream(saveFile);
int temp =0;
byte data[] =new byte[512];
while((temp=input.read(data,0,512))!=-1){
output.write(data);
}
}catch(IOException e){
throw e;
}finally{
try{
input.close();
output.close();
}catch(IOException e1){
throw e1;
}
}
}
}
return names;
}
}
通过一个例子来展示使用方法:
file.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="flieupload2.jsp" method="post"
enctype="multipart/form-data">
姓名:<input type="text" name="uname"><br>
兴趣:<input type="checkbox" name="inst" value="Swing">游泳
<input type="checkbox" name="inst" value="Sing">唱歌
<input type="checkbox" name="inst" value="Swim">化学
<br>
照片:<input type="file" name="pic1"><br>
照片:<input type="file" name="pic1"><br>
照片:<input type="file" name="pic1"><br>
<input type="submit" value="上传">
<input type="reset" value="重置">
</form>
</body>
</html>
fileupload.jsp:
<%@page import="fileupload.fileuploadTools"%>
<%@page contentType="text/html" pageEncoding="gbk" %>
<%@page import="java.util.*,java.io.*" %>
<%@page import ="org.apache.commons.fileupload.*" %>
<%@page import ="org.apache.commons.fileupload.disk.*" %>
<%@page import ="org.apache.commons.fileupload.servlet.*" %>
<%@page import ="webstudy.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
fileuploadTools fut = new
fileuploadTools(request,3*1024*1024,this.getServletContext().getRealPath("/")
+"uploadtemp" );
String name= fut.getParameter("uname");
String inst[] = fut.getParmeterValues("inst");
List<String> all=
fut.saveAll(this.getServletContext().getRealPath("/")+"upload"+java.io.File.separator);
%>
<h3>姓名:<%=name%></h3>
<h3>兴趣:
<%
for(int x=0;x<inst.length;x++){
%>
<%=inst[x]%>,
<%
}
%>
</h3>
<%
Iterator<String> iter = all.iterator();
while(iter.hasNext()){
%>
<img src="<%=this.getServletContext().getRealPath("/")%>upload/<%=iter.next() %>">
<%
}
%>
</body>
</html>