JSP 文件上传下载Word文档格式.docx
- 文档编号:16450787
- 上传时间:2022-11-23
- 格式:DOCX
- 页数:19
- 大小:112.07KB
JSP 文件上传下载Word文档格式.docx
《JSP 文件上传下载Word文档格式.docx》由会员分享,可在线阅读,更多相关《JSP 文件上传下载Word文档格式.docx(19页珍藏版)》请在冰豆网上搜索。
//cid-
132KB
视频:
//cid-16分31秒6.0MB
内容包括:
1.ApacheCommonsFileUpload项目介绍
2.下载并增加必要的类库
3.编写文件上传表单HTML
4.编写文件上传处理JSP
5.编写文件下载JSP
6.发布并测试
视频截图:
upload.htm
<
formname="
f1"
id="
action="
upload.jsp"
method="
post"
ENCTYPE="
multipart/form-data"
>
<
tableborder="
0"
tr>
td>
Login:
/td>
inputtype="
text"
name="
login"
/tr>
Password:
password"
tdvalign="
top"
附件:
br>
file"
tdcolspan="
2"
align="
center"
submit"
/table>
/form>
upload.jsp
%@pagelanguage="
java"
import="
java.util.*"
pageEncoding="
GBK"
%>
%@pageimport="
mons.fileupload.servlet.ServletFileUpload"
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("
out.println(name+"
="
+value);
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){
请选择一个文件来上传"
}else{
java.io.FileOutputStreamfout=newjava.io.FileOutputStream(
application.getRealPath("
upload/"
+getShortFileName(fileName)));
fout.write(item.get());
fout.close();
请用文件上传表单来访问这个页面"
相关资料:
下载地址
http:
//commons.apache.org/fileupload/
//commons.apache.org/io/
用法文档:
//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();
//Parsetherequest
List/*FileItem*/items=upload.parseRequest(request);
That'
sallthat'
sneeded.Really!
TheresultoftheparseisaListoffileitems,eachofwhichimplementstheFileIteminterface.Processingtheseitemsisdiscussedbelow.
Exercisingmorecontrol
Ifyourusagescenarioisclosetothesimplestcase,describedabove,butyouneedalittlemorecontrol,youcaneasilycustomizethebehavioroftheuploadhandlerorthefileitemfactoryorboth.Thefollowingexampleshowsseveralconfigurationoptions:
DiskFileItemFactoryfactory=newDiskFileItemFactory();
字
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- JSP 文件上传下载 文件 上传下载