jsp实现文件上传和下载 及留言板功能代码及说明Word文档格式.docx
《jsp实现文件上传和下载 及留言板功能代码及说明Word文档格式.docx》由会员分享,可在线阅读,更多相关《jsp实现文件上传和下载 及留言板功能代码及说明Word文档格式.docx(11页珍藏版)》请在冰豆网上搜索。
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;
*文件上传处理主程序。
&
#65533;
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!
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=\