JSP 文件上传下载.docx
- 文档编号:3545454
- 上传时间:2022-11-23
- 格式:DOCX
- 页数:19
- 大小:112.07KB
JSP 文件上传下载.docx
《JSP 文件上传下载.docx》由会员分享,可在线阅读,更多相关《JSP 文件上传下载.docx(19页珍藏版)》请在冰豆网上搜索。
JSP文件上传下载
MyEclipse6实战开发讲解视频入门10JSP文件上传下载
2007-12-2
本视频讲解了如何使用最新版本开源的ApacheCommonsFileUpload来上传文件以及如何编写文件下载代码.
视频部分代码屏幕出现闪烁,错位,不便之处请参考本文中的源码和文档中绿色部分的注释:
//Setfactoryconstraints
factory.setSizeThreshold(yourMaxMemorySize);//设置最多只允许在内存中存储的数据,单位:
字节
factory.setRepository(yourTempDirectory);//设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录(默认可以不用设置)
//Createanewfileuploadhandler
ServletFileUploadupload=newServletFileUpload(factory);
//Setoverallrequestsizeconstraint
//设置允许用户上传文件大小,单位:
字节
upload.setSizeMax(yourMaxRequestSize);
友情提示:
下载微软网盘文件时关闭下载工具, 否则你将得到错误的文件,双击EXE会出来DOS窗口.正确操作是点击文件名后能看到显示下载链接和文件大小等信息.
代码:
http:
//cid- 132KB
视频:
http:
//cid-16分31秒6.0MB
内容包括:
1.ApacheCommonsFileUpload项目介绍
2.下载并增加必要的类库
3.编写文件上传表单HTML
4.编写文件上传处理JSP
5.编写文件下载JSP
6.发布并测试
视频截图:
代码:
upload.htm
upload.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="GBK"%>
<%@pageimport="mons.fileupload.servlet.ServletFileUpload"%>
<%@pageimport="mons.fileupload.disk.DiskFileItemFactory"%>
<%!
/**
*得到文件的短路径,不包括目录.
*@date2005-10-18
*
*@paramfileName
* 需要处理的文件的名字.
*@returntheshortversionofthefile'sname.
*/
publicstaticStringgetShortFileName(StringfileName){
if(fileName!
=null){
StringoldFileName=newString(fileName);
fileName=fileName.replace('\\','/');
//Handledir
if(fileName.endsWith("/")){
intidx=fileName.indexOf('/');
if(idx==-1||idx==fileName.length()-1){
returnoldFileName;
}else{
returnoldFileName
.substring(idx+1,fileName.length()-1);
}
}
if(fileName.lastIndexOf("/")>0){
fileName=fileName.substring(fileName.lastIndexOf("/")+1,
fileName.length());
}
returnfileName;
}
return"";
}%>
<%
//Checkthatwehaveafileuploadrequest
booleanisMultipart=ServletFileUpload.isMultipartContent(request);
if(isMultipart){
//Createafactoryfordisk-basedfileitems
mons.fileupload.FileItemFactoryfactory=newDiskFileItemFactory();
//Createanewfileuploadhandler
ServletFileUploadupload=newServletFileUpload(factory);
//Parsetherequest
List/*FileItem*/items=upload.parseRequest(request);
//Processtheuploadeditems
Iteratoriter=items.iterator();
while(iter.hasNext()){
mons.fileupload.FileItemitem=(mons.fileupload.FileItem)iter
.next();
if(item.isFormField()){
Stringname=item.getFieldName();
Stringvalue=item.getString("GBK");
out.println(name+"="+value);
}else{
StringfieldName=item.getFieldName();//file
StringfileName=item.getName();
StringcontentType=item.getContentType();
booleanisInMemory=item.isInMemory();
longsizeInBytes=item.getSize();
out.println("上传的文件名是:
"+fileName);
if(fileName==null||fileName.length()==0){
out.println("请选择一个文件来上传");
}else{
java.io.FileOutputStreamfout=newjava.io.FileOutputStream(
application.getRealPath("upload/"
+getShortFileName(fileName)));
fout.write(item.get());
fout.close();
}
}
}
}else{
out.println("请用文件上传表单来访问这个页面");
}
%>
相关资料:
下载地址
http:
//commons.apache.org/fileupload/
http:
//commons.apache.org/io/
用法文档:
http:
//commons.apache.org/fileupload/using.html
UsingFileUpload
FileUploadcanbeusedinanumberofdifferentways,dependingupontherequirementsofyourapplication.Inthesimplestcase,youwillcallasinglemethodtoparsetheservletrequest,andthenprocessthelistofitemsastheyapplytoyourapplication.Attheotherendofthescale,youmightdecidetocustomizeFileUploadtotakefullcontrolofthewayinwhichindividualitemsarestored;forexample,youmightdecidetostreamthecontentintoadatabase.
Here,wewilldescribethebasicprinciplesofFileUpload,andillustratesomeofthesimpler-andmostcommon-usagepatterns.CustomizationofFileUploadisdescribedelsewhere.
FileUploaddependsonCommonsIO,somakesureyouhavetheversionmentionedonthedependenciespageinyourclasspathbeforecontinuing.
Howitworks
AfileuploadrequestcomprisesanorderedlistofitemsthatareencodedaccordingtoRFC1867,"Form-basedFileUploadinHTML".FileUploadcanparsesucharequestandprovideyourapplicationwithalistoftheindividualuploadeditems.EachsuchitemimplementstheFileIteminterface,regardlessofitsunderlyingimplementation.
ThispagedescribesthetraditionalAPIofthecommonsfileuploadlibrary.ThetraditionalAPIisaconvenientapproach.However,forultimateperformance,youmightpreferthefasterStreamingAPI.
Eachfileitemhasanumberofpropertiesthatmightbeofinterestforyourapplication.Forexample,everyitemhasanameandacontenttype,andcanprovideanInputStreamtoaccessitsdata.Ontheotherhand,youmayneedtoprocessitemsdifferently,dependinguponwhethertheitemisaregularformfield-thatis,thedatacamefromanordinarytextboxorsimilarHTMLfield-oranuploadedfile.TheFileIteminterfaceprovidesthemethodstomakesuchadetermination,andtoaccessthedatainthemostappropriatemanner.
FileUploadcreatesnewfileitemsusingaFileItemFactory.ThisiswhatgivesFileUploadmostofitsflexibility.Thefactoryhasultimatecontroloverhoweachitemiscreated.ThefactoryimplementationthatcurrentlyshipswithFileUploadstorestheitem'sdatainmemoryorondisk,dependingonthesizeoftheitem(i.e.bytesofdata).However,thisbehaviorcanbecustomizedtosuityourapplication.
ServletsandPortlets
Startingwithversion1.1,FileUploadsupportsfileuploadrequestsinbothservletandportletenvironments.Theusageisalmostidenticalinthetwoenvironments,sotheremainderofthisdocumentrefersonlytotheservletenvironment.
Ifyouarebuildingaportletapplication,thefollowingarethetwodistinctionsyoushouldmakeasyoureadthisdocument:
∙WhereyouseereferencestotheServletFileUploadclass,substitutethePortletFileUploadclass.
∙WhereyouseereferencestotheHttpServletRequestclass,substitutetheActionRequestclass.
Parsingtherequest
Beforeyoucanworkwiththeuploadeditems,ofcourse,youneedtoparsetherequestitself.Ensuringthattherequestisactuallyafileuploadrequestisstraightforward,butFileUploadmakesitsimplicityitself,byprovidingastaticmethodtodojustthat.
//Checkthatwehaveafileuploadrequest
booleanisMultipart=ServletFileUpload.isMultipartContent(request);
Nowwearereadytoparsetherequestintoitsconstituentitems.
Thesimplestcase
Thesimplestusagescenarioisthefollowing:
∙Uploadeditemsshouldberetainedinmemoryaslongastheyarereasonablysmall.
∙Largeritemsshouldbewrittentoatemporaryfileondisk.
∙Verylargeuploadrequestsshouldnotbepermitted.
∙Thebuilt-indefaultsforthemaximumsizeofanitemtoberetainedinmemory,themaximumpermittedsizeofanuploadrequest,andthelocationoftemporaryfilesareacceptable.
Handlingarequestinthisscenariocouldn'tbemuchsimpler:
//Createafactoryfordisk-basedfileitems
FileItemFactoryfactory=newDiskFileItemFactory();
//Createanewfileuploadhandler
ServletFileUploadupload=newServletFileUpload(factory);
//Parsetherequest
List/*FileItem*/items=upload.parseRequest(request);
That'sallthat'sneeded.Really!
TheresultoftheparseisaListoffileitems,eachofwhichimplementstheFileIteminterface.Processingtheseitemsisdiscussedbelow.
Exercisingmorecontrol
Ifyourusagescenarioisclosetothesimplestcase,describedabove,butyouneedalittlemorecontrol,youcaneasilycustomizethebehavioroftheuploadhandlerorthefileitemfactoryorboth.Thefollowingexampleshowsseveralconfigurationoptions:
//Createafactoryfordisk-basedfileitems
DiskFileItemFactoryfactory=newDiskFileItemFactory();
//Setfactoryconstraints
factory.setSizeThreshold(yourMaxMemorySize);//设置最多只允许在内存中存储的数据,单位:
字节
factory.setRepository(yourTempDirectory);//设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录(默认可以不用设置)
//Createanewfileuploadhandler
ServletFileUploadupload=newServletFileUpload(factory);
//Setoverallrequestsizeconstraint
//设置允许用户上传文件大小,单位:
字
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- JSP 文件上传下载 文件 上传下载
![提示](https://static.bdocx.com/images/bang_tan.gif)