JSP 文件上传下载.docx

上传人:b****5 文档编号:3545454 上传时间:2022-11-23 格式:DOCX 页数:19 大小:112.07KB
下载 相关 举报
JSP 文件上传下载.docx_第1页
第1页 / 共19页
JSP 文件上传下载.docx_第2页
第2页 / 共19页
JSP 文件上传下载.docx_第3页
第3页 / 共19页
JSP 文件上传下载.docx_第4页
第4页 / 共19页
JSP 文件上传下载.docx_第5页
第5页 / 共19页
点击查看更多>>
下载资源
资源描述

JSP 文件上传下载.docx

《JSP 文件上传下载.docx》由会员分享,可在线阅读,更多相关《JSP 文件上传下载.docx(19页珍藏版)》请在冰豆网上搜索。

JSP 文件上传下载.docx

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

 

   

     Login:

     

   

   

     Password:

     

   

   附件:


     

   

 

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

//设置允许用户上传文件大小,单位:

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 外语学习 > 日语学习

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1