Jsp页面实现文件上传下载.docx
《Jsp页面实现文件上传下载.docx》由会员分享,可在线阅读,更多相关《Jsp页面实现文件上传下载.docx(17页珍藏版)》请在冰豆网上搜索。
Jsp页面实现文件上传下载
Jsp页面实现文件上传下载
第1页jsp页面实现文件上传
代码开发的过程见用TOMCAT作简单的jspweb开发
名称:
jsp页面上传类
作者:
SinNeR
Mail:
vogoals[at]
特点:
1可以多文件上传;
2返回上传后的文件名;
3form表单中的其他参数也可以得到。
先贴上传类,JspFileUpload
packagecom.vogoal.util;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.text.SimpleDateFormat;
importjava.util.ArrayList;
importjava.util.Date;
importjava.util.Hashtable;
importjavax.servlet.ServletInputStream;
importjavax.servlet.http.HttpServletRequest;
/*
*vogoalAPI1.0
*AutherSinNeR@
*by
*mail:
vogoals@
*/
/**
*JSP上传文件类
*
*@authorSinNeR
*@version1.0
*/
publicclassJspFileUpload{
/**request对象*/
privateHttpServletRequestrequest=null;
/**上传文件的路径*/
privateStringuploadPath=null;
/**每次读取得字节的大小*/
privatestaticintBUFSIZE=1024*8;
/**存储参数的Hashtable*/
privateHashtableparamHt=newHasptable();
/**存储上传的文件的文件名的ArrayList*/
privateArrayListupdFileArr=newArrayList();
/**
*设定request对象。
*
*@paramrequest
*HttpServletRequestrequest对象
*/
publicvoidsetRequest(HttpServletRequestrequest){
this.request=request;
}
/**
*设定文件上传路径。
*
*@parampath
*用户指定的文件的上传路径。
*/
publicvoidsetUploadPath(Stringpath){
this.uploadPath=path;
}
/**
*文件上传处理主程序。
�������B
*
*@returnint操作结果0文件操作成功;1request对象不存在。
2没有设定文件保存路径或者文件保存路径不正确;3
*没有设定正确的enctype;4文件操作异常。
*/
publicintprocess(){
intstatus=0;
//文件上传前,对request对象,上传路径以及enctype进行check。
status=preCheck();
//出错的时候返回错误代码。
if(status!
=0)
returnstatus;
try{
//��参数或者文件名�u��
Stringname=null;
//参数的value
Stringvalue=null;
//读取的流是否为文件的标志位
booleanfileFlag=false;
//要存储的文件。
FiletmpFile=null;
//上传的文件的名字
StringfName=null;
FileOutputStreambaos=null;
BufferedOutputStreambos=null;
//��存储参数的Hashtable
paramHt=newHashtable();
updFileArr=newArrayList();
intrtnPos=0;
byte[]buffs=newbyte[BUFSIZE*8];
//�取得ContentType
StringcontentType=request.getContentType();
intindex=contentType.indexOf("boundary=");
Stringboundary="--"+contentType.substring(index+9);
StringendBoundary=boundary+"--";
//�从request对象中取得流。
ServletInputStreamsis=request.getInputStream();
//读取1行
while((rtnPos=sis.readLine(buffs,0,buffs.length))!
=-1){
StringstrBuff=newString(buffs,0,rtnPos);
//读取1行数据�n��
if(strBuff.startsWith(boundary)){
if(name!
=null&&name.trim().length()>0){
if(fileFlag){
bos.flush();
baos.close();
bos.close();
baos=null;
bos=null;
updFileArr.add(fName);
}else{
Objectobj=paramHt.get(name);
ArrayListal=newArrayList();
if(obj!
=null){
al=(ArrayList)obj;
}
al.add(value);
System.out.println(value);
paramHt.put(name,al);
}
}
name=newString();
value=newString();
fileFlag=false;
fName=newString();
rtnPos=sis.readLine(buffs,0,buffs.length);
if(rtnPos!
=-1){
strBuff=newString(buffs,0,rtnPos);
if(strBuff.toLowerCase().startsWith(
"content-disposition:
form-data;")){
intnIndex=strBuff.toLowerCase().indexOf(
"name=\"");
intnLastIndex=strBuff.toLowerCase().indexOf(
"\"",nIndex+6);
name=strBuff.substring(nIndex+6,nLastIndex);
}
intfIndex=strBuff.toLowerCase().indexOf(
"filename=\"");
if(fIndex!
=-1){
fileFlag=true;
intfLastIndex=strBuff.toLowerCase().indexOf(
"\"",fIndex+10);
fName=strBuff.substring(fIndex+10,fLastIndex);
fName=getFileName(fName);
if(fName==null||fName.trim().length()==0){
fileFlag=false;
sis.readLine(buffs,0,buffs.length);
sis.readLine(buffs,0,buffs.length);
sis.readLine(buffs,0,buffs.length);
continue;
}else{
fName=getFileNameByTime(fName);
sis.readLine(buffs,0,buffs.length);
sis.readLine(buffs,0,buffs.length);
}
}
}
}elseif(strBuff.startsWith(endBoundary)){
if(name!
=null&&name.trim().length()>0){
if(fileFlag){
bos.flush();
baos.close();
bos.close();
baos=null;
bos=null;
updFileArr.add(fName);
}else{
Objectobj=paramHt.get(name);
ArrayListal=newArrayList();
if(obj!
=null){
al=(ArrayList)obj;
}
al.add(value);
paramHt.put(name,al);
}
}
}else{
if(fileFlag){
if(baos==null&&bos==null){
tmpFile=newFile(uploadPath+fName);
baos=newFileOutputStream(tmpFile);
bos=newBufferedOutputStream(baos);
}
bos.write(buffs,0,rtnPos);
baos.flush();
}else{
System.out.println("test:
"+value+"--"+strBuff);
value=value+strBuff;
}
}
}
}catch(IOExceptione){
status=4;
}
returnstatus;
}
privateintpreCheck(){
interrCode=0;
if(request==null)
return1;
if(uploadPath==null||uploadPath.trim().length()==0)
return2;
else{
FiletmpF=newFile(uploadPath);
if(!
tmpF.exists())
return2;
}
StringcontentType=request.getContentType();
if(contentType.indexOf("multipart/form-data")==-1)
return3;
returnerrCode;
}
publicStringgetParameter(Stringname){
Stringvalue="";
if(name==null||name.trim().length()==0)
returnvalue;
value=(paramHt.get(name)==null)?
"":
(String)((ArrayList)paramHt.get(name)).get(0);
returnvalue;
}
publicString[]getParameters(Stringname){
if(name==null||name.trim().length()==0)
returnnull;
if(paramHt.get(name)==null)
returnnull;
ArrayListal=(ArrayList)paramHt.get(name);
String[]strArr=newString[al.size()];
for(inti=0;istrArr[i]=(String)al.get(i);
returnstrArr;
}
publicintgetUpdFileSize(){
returnupdFileArr.size();
}
publicString[]getUpdFileNames(){
String[]strArr=newString[updFileArr.size()];
for(inti=0;istrArr[i]=(String)updFileArr.get(i);
returnstrArr;
}
privateStringgetFileName(Stringinput){
intfIndex=input.lastIndexOf("\\");
if(fIndex==-1){
fIndex=input.lastIndexOf("/");
if(fIndex==-1){
returninput;
}
}
input=input.substring(fIndex+1);
returninput;
}
privateStringgetFileNameByTime(Stringinput){
intindex=input.indexOf(".");
Datedt=newDate();
SimpleDateFormatsdf=newSimpleDateFormat("yyyyMMddHHmmssSSS");
returninput.substring(0,index)+sdf.format(dt)+input.substring(index);
}
}
说明:
这个类基本解决了上一贴的上一贴说的存在的bug和不足。
主要做了如下修正。
4用户可以设定文件上传的路径,这里没有用request对象的getRealPath方法来取得相对路径,而是用了绝对路径。
是一个小败笔。
因为有时候用户只是得到服务器的一个应用,而不知道整个服务器的路径。
但是既然getRealPath自己可以得到,用户自己取得也可以。
5在文件上传处理的时候,预先进行了check,把一些可能出现的造成上传失败的情况拍查掉。
避免该类出现不该出现的异常。
6捕获了IO异常,避免文件上传的时候出现异常时程序的不友好表现
7提供了方法返回form表单中其他参数的取得,模拟了HttpServletRequest对象的getParameter和getParameters方法(后面这个方法是叫这个名字么-_-b),取得Parameter的名称的方法没有提供,是个小缺陷。
8提供了方法返回上传的文件的件数和上传的文件名,方便用户作其他操作。
现在介绍下JSP页面中如何用这个类实现上传。
首先,要把这个类编译后的class文件拷贝到WEB-INF/classes/目录下。
注意保持package的结构。
在jsp页面中引用这个类
<%@pageimport="com.vogoal.util.JspFileUpload"%>
<%
//初始化
JspFileUploadjfu=newJspFileUpload();
//设定request对象
jfu.setRequest(request);
//设定上传的文件路径
jfu.setUploadPath("C:
\\");
//上传处理
intrtn=jfu.process();
//取得form中其他input控件参数的值
Stringusername=jfu.getParameter("username");
//如果对应同一个参数有多个input控件,返回数组
String[]usernameArr=jfu.getParameters("username");
//取得上传的文件的名字
String[]fileArr=jfu.getUpdFileNames();
//取得上传文件的个数,这个方法有点鸡肋
intfileNumber=jfu.getUpdFileSize();
//下面的是测试输出的代码。
//out.println("parameter:
"+username);
//out.println("parametersize:
"+usernameArr.length);
//out.println("fileArrsize:
"+fileArr.length);
//if(fileArr.length>0)
//out.println("fileArr0:
"+fileArr[0]);
%>
使用的时候的注意事项:
9一定要设定request对象。
10一定要设定正确的上传路径。
11执行完了之后才可以得到其他参数,因为执行了之后这些参数才被分析。
1,2两点如果没有做到的话,process方法执行的时候汇报错。
各个用户可用的方法及说明:
设定requet对象。
publicvoidsetRequest(HttpServletRequestrequest)
设定文件上传的路径。
publicvoidsetUploadPath(Stringpath)
文件上传处理主程序。
@returnint操作结果0文件操作成功;1request对象不存在。
2没有设定文件保存路径或者文件保存路径不正确;3没有设定正确的enctype;4文件操作异常。
publicintprocess()
根据name取得form表单中其他传递的参数的值(多个的话返回其中一个)
publicStringgetParameter(Stringname)
根据name取得form表单中其他传递的参数的值(返回数组,可有多个)
publicString[]getParameters(Stringname)
取得上传成功文件的个数
publicintgetUpdFileSize()
取得上传的文件名对应的数组。
publicString[]getUpdFileNames()
注意process方法地返回值,在不是0的情况下操作失败。
以下提供测试类以及测试页面(见附件):
HelloPostFile.html
HelloPostFile.jsp
写在jsp中的代码的测试文件。
HelloPostFileWithClass.html
HelloPostFileWithClass.jsp
抽出class后的测试文件。
src在
WEB-INF/src/
class在
WEB-INF/classes/
另:
由于这个文件被我在中文日文系统下编辑过,注释出现乱码,所以大部分都删掉了,见谅。
原码:
jspUpload
第2页jsp页面实现文件下载
JSP文件下载类整理完成。
可以在JSP页面中实现简单的下载,支持文件打包下载功能。
支持将字符串或者流生成文件提供下载的功能。
但是也有一些缺点。
现把这个类的基本介绍总结如下。
名称:
jsp页面下载类
作者:
SinNeR
Mail:
vogoals[at]
特点及功能介绍:
1支持单文件下载。
支持多文件zip压缩下载。
多文件zip压缩可在服务器保留或者删除副本。
支持将特定的字符串或者byte数组以指定的文件名提供下载。
2在下载过程中需要提供response对象。
并且选择下载形式。
3下载处理前先进行check,避免出现错误。
4下载处理过程中出错时,会报告错误信息。
5日文系统下文件名是中文时出现乱码问题。
6处理前需要进行相对繁琐的设定。
现介绍下使用者可见的方法的功能。
设定实现下载必须的response对象。
publicvoidsetResponse(HttpServletResponseresponse)
设定下载方式:
0为普通单文件下载。
1为多文件压缩成zip包下载。
2为将指定的字符串等拼接成文件内容提供给用户下载。
publicvoidsetDownType(intfileType)
设定下载时显示给用的文件名。
publicvoidsetDisFileName(StringfileName)
压缩文件下载时,设定压缩文件暂时保存的路径(路径为绝对路径)
publicvoidsetZipFilePath(Stringpath)
压缩文件下载时,设定服务器端生成的压缩文件是否删除。
True删除;false保留。
publicvoidsetZipDelFlag(booleanb)
压缩文件下载时,设定要压缩的文件的文件路径(路径为绝对路径)
publicvoidsetZipFileNames(String[]fileNames)
单文件下载时,设定下载文件的路径(绝对路径)
publicvoidsetDownFileName(StringfileName)
将字符串生成文件内容模拟下载时,设定文件的内容。
参数为字符串(可多次调用)
publicintsetFileContent(StringfileContent)
将字符串生成文件内容模拟下载时,设定文件的内容。
参数为byte数组(可多次调用)
返回