Java 文件上传的实例详解
Java文件上传的实例详解
java文件上传
Java文件上传,介绍几种常用的方法,也是经过本人亲手调试过的
1.jspsmartupload
这个组件用起来是挺方便的,不过就是只适合小文件上传,如果大文件上传的话就不行,查看了一下他的代码,m_totalBytes=m_request.getContentLength();m_binArray=newbyte[m_totalBytes];居然把整个上传文件都读到内存去了,那如果是上传几十M的文件,同时几个用户上传,服务器稳挂,不过如果只是上传5M以内的小文件,这个组件还是挺实用的
下面是源代码:
File类
/*
*创建日期2006-7-29
*
*更改所生成文件模板为
*窗口>首选项>Java>代码生成>代码和注释
*/
packagecom.kinstar.issuing.file;
/**
*@authorgongyifeng
*
*更改所生成类型注释的模板为
*窗口>首选项>Java>代码生成>代码和注释
*/
importjava.io.ByteArrayInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.math.BigInteger;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.text.DateFormat;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjavax.servlet.ServletException;
//Referencedclassesofpackagecom.jspsmart.upload:
//SmartUploadException,SmartUpload
publicclassFile{
privateSmartUploadm_parent;
privateintm_startData;
privateintm_endData;
privateintm_size;
privateStringm_fieldname;
privateStringm_filename;
privateStringm_fileExt;
privateStringm_filePathName;
privateStringm_contentType;
privateStringm_contentDisp;
privateStringm_typeMime;
privateStringm_subTypeMime;
privateStringm_contentString;
privatebooleanm_isMissing;
publicstaticfinalintSAVEAS_AUTO=0;
publicstaticfinalintSAVEAS_VIRTUAL=1;
publicstaticfinalintSAVEAS_PHYSICAL=2;
File(){
m_startData=0;
m_endData=0;
m_size=0;
m_fieldname=newString();
m_filename=newString();
m_fileExt=newString();
m_filePathName=newString();
m_contentType=newString();
m_contentDisp=newString();
m_typeMime=newString();
m_subTypeMime=newString();
m_contentString=newString();
m_isMissing=true;
}
publicvoidsaveAs(Strings)throwsIOException,SmartUploadException{
saveAs(s,0);
}
publicvoidsaveAs(Strings,inti)throwsIOException,SmartUploadException{
Strings1=newString();
s1=m_parent.getPhysicalPath(s,i);
if(s1==null)
thrownewIllegalArgumentException("Thereisnospecifieddestinationfile(1140).");
try
{
java.io.Filefile=newjava.io.File(s1);
FileOutputStreamfileoutputstream=newFileOutputStream(file);
fileoutputstream.write(m_parent.m_binArray,m_startData,m_size);
fileoutputstream.close();
}
catch(IOExceptionioexception)
{
thrownewSmartUploadException("Filecan'tbesaved(1120).");
}
}
publicvoidfileToField(ResultSetresultset,Strings)throwsServletException,IOException,SmartUploadException,SQLException{
longl=0L;
inti=0x10000;
intj=0;
intk=m_startData;
if(resultset==null)
thrownewIllegalArgumentException("TheRecordSetcannotbenull(1145).");
if(s==null)
thrownewIllegalArgumentException("ThecolumnNamecannotbenull(1150).");
if(s.length()==0)
thrownewIllegalArgumentException("ThecolumnNamecannotbeempty(1155).");
l=BigInteger.valueOf(m_size).divide(BigInteger.valueOf(i)).longValue();
j=BigInteger.valueOf(m_size).mod(BigInteger.valueOf(i)).intValue();
try
{
for(inti1=1;(long)i10)
resultset.updateBinaryStream(s,newByteArrayInputStream(m_parent.m_binArray,k,j),j);
}catch(SQLExceptionsqlexception){
byteabyte0[]=newbyte[m_size];
System.arraycopy(m_parent.m_binArray,m_startData,abyte0,0,m_size);
resultset.updateBytes(s,abyte0);
}catch(Exceptionexception)
{
thrownewSmartUploadException("UnabletosavefileintheDataBase(1130).");
}
}
publicbooleanisMissing(){
returnm_isMissing;
}
publicStringgetFieldName(){
returnm_fieldname;
}
publicStringgetFileName(){
DateFormatdf=newSimpleDateFormat("yyyyMMddHHmmss");
Stringdate=df.format(newDate());
returndate+m_filename;
}
publicStringgetFilePathName(){
returnm_filePathName;
}
publicStringgetFileExt(){
returnm_fileExt;
}
publicStringgetContentType(){
returnm_contentType;
}
publicStringgetContentDisp(){
returnm_contentDisp;
}
publicStringgetContentString(){
Strings=newString(m_parent.m_binArray,m_startData,m_size);
returns;
}
publicStringgetTypeMIME()throwsIOException{
returnm_typeMime;
}
publicStringgetSubTypeMIME(){
returnm_subTypeMime;
}
publicintgetSize(){
returnm_size;
}
protectedintgetStartData(){
returnm_startData;
}
protectedintgetEndData(){
returnm_endData;
}
protectedvoidsetParent(SmartUploadsmartupload){
m_parent=smartupload;
}
protectedvoidsetStartData(inti){
m_startData=i;
}
protectedvoidsetEndData(inti){
m_endData=i;
}
protectedvoidsetSize(inti){
m_size=i;
}
protectedvoidsetIsMissing(booleanflag){
m_isMissing=flag;
}
protectedvoidsetFieldName(Strings){
m_fieldname=s;
}
protectedvoidsetFileName(Strings){
m_filename=s;
}
protectedvoidsetFilePathName(Strings){
m_filePathName=s;
}
protectedvoidsetFileExt(Strings){
m_fileExt=s;
}
protectedvoidsetContentType(Strings){
m_contentType=s;
}
protectedvoidsetContentDisp(Strings){
m_contentDisp=s;
}
protectedvoidsetTypeMIME(Strings){
m_typeMime=s;
}
protectedvoidsetSubTypeMIME(Strings){
m_subTypeMime=s;
}
publicbytegetBinaryData(inti){
if(m_startData+i>m_endData)
thrownewArrayIndexOutOfBoundsException("IndexOutofrange(1115).");
if(m_startData+i<=m_endData)
returnm_parent.m_binArray[m_startData+i];
else
return0;
}
}
Files类
/*
*创建日期2006-7-29
*
*更改所生成文件模板为
*窗口>首选项>Java>代码生成>代码和注释
*/
packagecom.kinstar.issuing.file;
/**
*@authorgongyifeng
*
*更改所生成类型注释的模板为
*窗口>首选项>Java>代码生成>代码和注释
*/
importjava.io.IOException;
importjava.util.*;
//Referencedclassesofpackagecom.jspsmart.upload:
//File,SmartUpload
publicclassFiles{
privateSmartUploadm_parent;
privateHashtablem_files;
privateintm_counter;
Files(){
m_files=newHashtable();
m_counter=0;
}
protectedvoidaddFile(Filefile){
if(file==null)
{
thrownewIllegalArgumentException("newFilecannotbenull.");
}else{
m_files.put(newInteger(m_counter),file);
m_counter++;
return;
}
}
publicFilegetFile(inti)
{
if(i<0)
thrownewIllegalArgumentException("File'sindexcannotbeanegativevalue(1210).");
Filefile=(File)m_files.get(newInteger(i));
if(file==null)
thrownewIllegalArgumentException("Files'nameisinvalidordoesnotexist(1205).");
else
returnfile;
}
publicintgetCount()
{
returnm_counter;
}
publiclonggetSize()throwsIOException
{
longl=0L;
for(inti=0;i
Request类
/*
*创建日期2006-7-29
*
*更改所生成文件模板为
*窗口>首选项>Java>代码生成>代码和注释
*/
packagecom.kinstar.issuing.file;
/**
*@authorgongyifeng
*
*更改所生成类型注释的模板为
*窗口>首选项>Java>代码生成>代码和注释
*/
importjava.util.Enumeration;
importjava.util.Hashtable;
publicclassRequest
{
privateHashtablem_parameters;
privateintm_counter;
Request(){
m_parameters=newHashtable();
m_counter=0;
}
protectedvoidputParameter(Strings,Strings1){
if(s==null)
thrownewIllegalArgumentException("Thenameofanelementcannotbenull.");
if(m_parameters.containsKey(s))
{
Hashtablehashtable=(Hashtable)m_parameters.get(s);
hashtable.put(newInteger(hashtable.size()),s1);
}else{
Hashtablehashtable1=newHashtable();
hashtable1.put(newInteger(0),s1);
m_parameters.put(s,hashtable1);
m_counter++;
}
}
publicStringgetParameter(Strings){
if(s==null)
thrownewIllegalArgumentException("Form'snameisinvalidordoesnotexist(1305).");
Hashtablehashtable=(Hashtable)m_parameters.get(s);
if(hashtable==null)
returnnull;
else
return(String)hashtable.get(newInteger(0));
}
publicEnumerationgetParameterNames()
{
returnm_parameters.keys();
}
publicString[]getParameterValues(Strings)
{
if(s==null)
thrownewIllegalArgumentException("Form'snameisinvalidordoesnotexist(1305).");
Hashtablehashtable=(Hashtable)m_parameters.get(s);
if(hashtable==null)
returnnull;
Stringas[]=newString[hashtable.size()];
for(inti=0;i
SmartUpload类
/*
*创建日期2006-7-29
*
*更改所生成文件模板为
*窗口>首选项>Java>代码生成>代码和注释
*/
packagecom.kinstar.issuing.file;
/**
*@authorgongyifeng
*
*更改所生成类型注释的模板为
*窗口>首选项>Java>代码生成>代码和注释
*/
importjava.io.*;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.util.Vector;
importjavax.servlet.*;
importjavax.servlet.http.*;
importjavax.servlet.jsp.JspWriter;
importjavax.servlet.jsp.PageContext;
//Referencedclassesofpackagecom.jspsmart.upload:
//Files,Request,SmartUploadException,File
publicclassSmartUpload
{
protectedbytem_binArray[];
protectedHttpServletRequestm_request;
protectedHttpServletResponsem_response;
protectedServletContextm_application;
privateintm_totalBytes;
privateintm_currentIndex;
privateintm_startData;
privateintm_endData;
privateStringm_boundary;
privatelongm_totalMaxFileSize;
privatelongm_maxFileSize;
privateVectorm_deniedFilesList;
privateVectorm_allowedFilesList;
privatebooleanm_denyPhysicalPath;
privatebooleanm_forcePhysicalPath;
privateStringm_contentDisposition;
publicstaticfinalintSAVE_AUTO=0;
publicstaticfinalintSAVE_VIRTUAL=1;
publicstaticfinalintSAVE_PHYSICAL=2;
privateFilesm_files;
privateRequestm_formRequest;
publicSmartUpload()
{
m_totalBytes=0;
m_currentIndex=0;
m_startData=0;
m_endData=0;
m_boundary=newString();
m_totalMaxFileSize=0L;
m_maxFileSize=0L;
m_deniedFilesList=newVector();
m_allowedFilesList=newVector();
m_denyPhysicalPath=false;
m_forcePhysicalPath=false;
m_contentDisposition=newString();
m_files=newFiles();
m_formRequest=newRequest();
}
publicfinalvoidinit(ServletConfigservletconfig)throwsServletException
{
m_application=servletconfig.getServletContext();
}
publicvoidservice(HttpServletRequesthttpservletrequest,HttpServletResponsehttpservletresponse)throwsServletException,IOException
{
m_request=httpservletrequest;
m_response=httpservletresponse;
}
publicfinalvoidinitialize(ServletConfigservletconfig,HttpServletRequesthttpservletrequest,HttpServletResponsehttpservletresponse)throwsServletException
{
m_application=servletconfig.getServletContext();
m_request=httpservletrequest;
m_response=httpservletresponse;
}
publicfinalvoidinitialize(PageContextpagecontext)throwsServletException
{
m_application=pagecontext.getServletContext();
m_request=(HttpServletRequest)pagecontext.getRequest();
m_response=(HttpServletResponse)pagecontext.getResponse();
}
publicfinalvoidinitialize(ServletContextservletcontext,HttpSessionhttpsession,HttpServletRequesthttpservletrequest,HttpServletResponsehttpservletresponse,JspWriterjspwriter)throwsServletException
{
m_application=servletcontext;
m_request=httpservletrequest;
m_response=httpservletresponse;
}
publicvoidupload()throwsServletException,IOException,SmartUploadException
{
inti=0;
booleanflag=false;
longl=0L;
booleanflag1=false;
Strings=newString();
Strings2=newString();
Strings4=newString();
Strings5=newString();
Strings6=newString();
Strings7=newString();
Strings8=newString();
Strings9=newString();
Strings10=newString();
booleanflag2=false;
m_totalBytes=m_request.getContentLength();
m_binArray=newbyte[m_totalBytes];
intj;
for(;i0;
Strings3=getDataFieldValue(s1,"name");
if(flag3)
{
s6=getDataFieldValue(s1,"filename");
s4=getFileName(s6);
s5=getFileExt(s4);
s7=getContentType(s1);
s8=getContentDisp(s1);
s9=getTypeMIME(s7);
s10=getSubTypeMIME(s7);
}
getDataSection();
if(flag3&&s4.length()>0)
{
if(m_deniedFilesList.contains(s5))
thrownewSecurityException("Theextensionofthefileisdeniedtobeuploaded(1015).");
if(!m_allowedFilesList.isEmpty()&&!m_allowedFilesList.contains(s5))
thrownewSecurityException("Theextensionofthefileisnotallowedtobeuploaded(1010).");
if(m_maxFileSize>0L&&(long)((m_endData-m_startData)+1)>m_maxFileSize)
thrownewSecurityException("Sizeexceededforthisfile:"+s4+"(1105).");
l+=(m_endData-m_startData)+1;
if(m_totalMaxFileSize>0L&&l>m_totalMaxFileSize)
thrownewSecurityException("TotalFileSizeexceeded(1110).");
}
if(flag3)
{
com.kinstar.issuing.file.Filefile=newcom.kinstar.issuing.file.File();
file.setParent(this);
file.setFieldName(s3);
file.setFileName(s4);
file.setFileExt(s5);
file.setFilePathName(s6);
file.setIsMissing(s6.length()==0);
file.setContentType(s7);
file.setContentDisp(s8);
file.setTypeMIME(s9);
file.setSubTypeMIME(s10);
if(s7.indexOf("application/x-macbinary")>0)
m_startData=m_startData+128;
file.setSize((m_endData-m_startData)+1);
file.setStartData(m_startData);
file.setEndData(m_endData);
m_files.addFile(file);
}else
{
Strings11=newString(m_binArray,m_startData,(m_endData-m_startData)+1);
m_formRequest.putParameter(s3,s11);
}
if((char)m_binArray[m_currentIndex+1]=='-')
break;
}
}
publicintsave(Strings)throwsServletException,IOException,SmartUploadException
{
returnsave(s,0);
}
publicintsave(Strings,inti)throwsServletException,IOException,SmartUploadException
{
intj=0;
if(s==null)
s=m_application.getRealPath("/");
if(s.indexOf("/")!=-1)
{
if(s.charAt(s.length()-1)!='/')
s=s+"/";
}else
if(s.charAt(s.length()-1)!='\\')
s=s+"\\";
for(intk=0;k0)
{
intj=i+s2.length();
intk=j;
s2="\"";
intl=s.indexOf(s2,j);
if(k>0&&l>0)
s3=s.substring(k,l);
}
returns3;
}
privateStringgetFileExt(Strings)
{
Strings1=newString();
inti=0;
intj=0;
if(s==null)
returnnull;
i=s.lastIndexOf(46)+1;
j=s.length();
s1=s.substring(i,j);
if(s.lastIndexOf(46)>0)
returns1;
else
return"";
}
privateStringgetContentType(Strings)
{
Strings1=newString();
Strings2=newString();
inti=0;
booleanflag=false;
s1="Content-Type:";
i=s.indexOf(s1)+s1.length();
if(i!=-1)
{
intj=s.length();
s2=s.substring(i,j);
}
returns2;
}
privateStringgetTypeMIME(Strings)
{
Strings1=newString();
inti=0;
i=s.indexOf("/");
if(i!=-1)
returns.substring(1,i);
else
returns;
}
privateStringgetSubTypeMIME(Strings)
{
Strings1=newString();
inti=0;
booleanflag=false;
i=s.indexOf("/")+1;
if(i!=-1)
{
intj=s.length();
returns.substring(i,j);
}else
{
returns;
}
}
privateStringgetContentDisp(Strings)
{
Strings1=newString();
inti=0;
intj=0;
i=s.indexOf(":")+1;
j=s.indexOf(";");
s1=s.substring(i,j);
returns1;
}
privatevoidgetDataSection()
{
booleanflag=false;
Strings=newString();
inti=m_currentIndex;
intj=0;
intk=m_boundary.length();
m_startData=m_currentIndex;
m_endData=0;
while(i=0)
{
s1=s.substring(0,s.lastIndexOf("\\"));
s2=s.substring(s.lastIndexOf("\\")+1);
}
if(s.lastIndexOf("/")>=0)
{
s1=s.substring(0,s.lastIndexOf("/"));
s2=s.substring(s.lastIndexOf("/")+1);
}
s1=s1.length()!=0?s1:"/";
java.io.Filefile=newjava.io.File(s1);
if(file.exists())
flag=true;
if(i==0)
{
if(isVirtual(s1))
{
s1=m_application.getRealPath(s1);
if(s1.endsWith(s3))
s1=s1+s2;
else
s1=s1+s3+s2;
returns1;
}
if(flag)
{
if(m_denyPhysicalPath)
thrownewIllegalArgumentException("Physicalpathisdenied(1125).");
else
returns;
}else
{
thrownewIllegalArgumentException("Thispathdoesnotexist(1135).");
}
}
if(i==1)
{
if(isVirtual(s1))
{
s1=m_application.getRealPath(s1);
if(s1.endsWith(s3))
s1=s1+s2;
else
s1=s1+s3+s2;
returns1;
}
if(flag)
thrownewIllegalArgumentException("Thepathisnotavirtualpath.");
else
thrownewIllegalArgumentException("Thispathdoesnotexist(1135).");
}
if(i==2)
{
if(flag)
if(m_denyPhysicalPath)
thrownewIllegalArgumentException("Physicalpathisdenied(1125).");
else
returns;
if(isVirtual(s1))
thrownewIllegalArgumentException("Thepathisnotaphysicalpath.");
else
thrownewIllegalArgumentException("Thispathdoesnotexist(1135).");
}else
{
returnnull;
}
}
publicvoiduploadInFile(Strings)throwsIOException,SmartUploadException
{
inti=0;
intj=0;
booleanflag=false;
if(s==null)
thrownewIllegalArgumentException("Thereisnospecifieddestinationfile(1025).");
if(s.length()==0)
thrownewIllegalArgumentException("Thereisnospecifieddestinationfile(1025).");
if(!isVirtual(s)&&m_denyPhysicalPath)
thrownewSecurityException("Physicalpathisdenied(1035).");
i=m_request.getContentLength();
m_binArray=newbyte[i];
intk;
for(;j
SmartUploadException类
/*
*创建日期2006-7-29
*
*更改所生成文件模板为
*窗口>首选项>Java>代码生成>代码和注释
*/
packagecom.kinstar.issuing.file;
/**
*@authorgongyifeng
*
*更改所生成类型注释的模板为
*窗口>首选项>Java>代码生成>代码和注释
*/
publicclassSmartUploadExceptionextendsException
{
SmartUploadException(Strings)
{
super(s);
}
}
上传的Servlet
packagecom.kinstar.issuing.action;
importjava.io.IOException;
importjavax.servlet.Servlet;
importjavax.servlet.ServletException;
importjava.io.*;
importjava.sql.SQLException;
importjava.util.*;
importjava.text.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importcom.kinstar.issuing.file.File;
importcom.kinstar.issuing.file.SmartUpload;
importcom.kinstar.issuing.objects.t_user;
importcom.kinstar.issuing.operation.UserOperation;
importcom.kinstar.issuing.program.programService;
importcom.kinstar.issuing.session.SessionGloble;
importcom.kinstar.issuing.util.StringUtil;
/**
*@version1.0
*@authorgyf
*/
publicclassupload2ProgramActionextendsHttpServlet{
privateServletConfigconfig;
/**
*初始化Servlet
*/
finalpublicvoidinit(ServletConfigconfig)throwsServletException{
this.config=config;
}
/**
*处理GET请求
*/
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
doPost(request,response);
}
/**
*响应POST请求
*/
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
intcount=0;
SmartUploadmySmartUpload=newSmartUpload();
try{
//初始化
mySmartUpload.initialize(config,request,response);
//上载
mySmartUpload.upload();
com.kinstar.issuing.file.Filef1=mySmartUpload.getFiles().getFile(0);
//com.kinstar.issuing.file.Filef2=mySmartUpload.getFiles().getFile(1);
StringbackPic=f1.getFileName();
//Stringname2=f2.getFileName();
longsize=0;
//保存上载文件到指定目录
count=mySmartUpload.save("ads");
response.sendRedirect("program.jsp?dopass=ture");
}
catch(Exceptione){
response.sendRedirect("fail.jsp");
}
}
2.common-fileupload组件
挺好用的,也能够上传大文件,我试过,300M以上的文件上传本地传非常快,异地测试也能够上传成功.
首先要下载org.apache.commons.fileupload包和org.apache.commons.io包
下面是我的servlet
packagecom.kinstar.issuing.action;
importjava.io.IOException;
importjavax.servlet.Servlet;
importjavax.servlet.ServletException;
importjava.io.*;
importjava.sql.SQLException;
importjava.util.*;
importjava.text.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
importjava.util.regex.*;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.commons.fileupload.DiskFileUpload;
importorg.apache.commons.fileupload.FileItem;
importorg.apache.commons.fileupload.FileUploadException;
importcom.kinstar.issuing.objects.t_user;
importcom.kinstar.issuing.operation.UserOperation;
importcom.kinstar.issuing.program.programService;
importcom.kinstar.issuing.session.SessionGloble;
importcom.kinstar.issuing.util.StringUtil;
/**
*@version1.0
*@authorgyf
*/
publicclassuploadProgramActionextendsHttpServlet{
privatestaticfinalStringCONTENT_TYPE="text/html;charset=GB2312";
/**
*处理GET请求
*/
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
doPost(request,response);
}
/**
*响应POST请求
*/
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
//变量定义
response.setContentType(CONTENT_TYPE);
HttpSessionmodifysession=request.getSession();
SessionGloblelogonUser;
logonUser=(SessionGloble)modifysession.getAttribute("UserInfo");
if(logonUser==null){
response.sendRedirect("mainindex.jsp");
}
t_useruserinfo=newt_user();
UserOperationuser=null;
try{
user=newUserOperation();
}catch(Exceptione1){
//TODO自动生成catch块
e1.printStackTrace();
}
try{
userinfo=user.getUser(logonUser.getUserId());
}catch(Exceptione2){
//TODO自动生成catch块
e2.printStackTrace();
}
//System.out.println("figure="+userinfo.getUserFigure());
PrintWriterout=response.getWriter();
DateFormatupdf=newSimpleDateFormat("yyyyMMddHHmm");
StringupdateTime=updf.format(newDate());
intisNeed=0;
StringIsCheck="0";
//省农行用户上传的节目必需显示,且审批已经合格
if(userinfo.getUserFigure().equals("1")){
isNeed=1;
IsCheck="1";
}
else{
isNeed=0;
IsCheck="0";
}
inttype=0;
StringavaTime="";
Stringscreen="";
intfileTime=0;
intfileTimeReal=0;
intcircle=0;
StringpicSwitch="";
StringdeleState="1";
StringbackPic="";
StringfieldName="";
StringfinalName="";
StringfileNameReal="";
longsize=0;
Stringname="";
try{
DiskFileUploadfu=newDiskFileUpload();
//设置允许用户上传文件大小,单位:字节,这里设为2m
fu.setSizeMax(5*1024*1024*1024);
//设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(10*1024*1024);
//设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath("C:\\WINDOWS\\Temp\\");
//开始读取上传信息
ListfileItems=fu.parseRequest(request);
//依次处理每个上传的文件
Iteratoriter=fileItems.iterator();
//正则匹配,过滤路径取文件名
StringregExp=".+\\\\(.+)$";
//过滤掉的文件类型
String[]errorType={".exe",".com",".cgi",".asp"};
Patternp=Pattern.compile(regExp);
StringUtilsu=newStringUtil();
while(iter.hasNext()){
FileItemitem=(FileItem)iter.next();
if(item.isFormField()){
//获得表单域的名字
fieldName=item.getFieldName();
//如果表单域的名字是name…
if(fieldName.equals("type"))
type=Integer.parseInt(item.getString());
}
if(!item.isFormField()){
name=item.getName();
size=item.getSize();
if((name==null||name.equals(""))&&size==0)
continue;
Matcherm=p.matcher(name);
booleanresult=m.find();
if(result){
for(inttemp=0;temp
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!