这篇文章主要介绍了java 文件上传的实例详解的相关资料,希望通过本文大家能掌握这部分内容,使用几种文件上传的方法,需要的朋友可以参考下
java 文件上传的实例详解
java 文件上传
java文件上传,介绍几种常用的方法,也是经过本人亲手调试过的
1.jspsmartupload
这个组件用起来是挺方便的,不过就是只适合小文件上传,如果大文件上传的话就不行,查看了一下他的代码,m_totalbytes = m_request.getcontentlength(); m_binarray = new byte[m_totalbytes];居然把整个上传文件都读到内存去了,那如果是上传几十m的文件,同时几个用户上传,服务器稳挂,不过如果只是上传5m以内的小文件,这个组件还是挺实用的
下面是源代码:
file类
/*
* 创建日期 2006-7-29
*
* 更改所生成文件模板为
* 窗口 > 首选项 > java > 代码生成 > 代码和注释
*/
package com.kinstar.issuing.file;
/**
* @author gongyifeng
*
* 更改所生成类型注释的模板为
* 窗口 > 首选项 > java > 代码生成 > 代码和注释
*/
import java.io.bytearrayinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.math.biginteger;
import java.sql.resultset;
import java.sql.sqlexception;
import java.text.dateformat;
import java.text.simpledateformat;
import java.util.date;
import javax.servlet.servletexception;
// referenced classes of package com.jspsmart.upload:
// smartuploadexception, smartupload
public class file{
private smartupload m_parent;
private int m_startdata;
private int m_enddata;
private int m_size;
private string m_fieldname;
private string m_filename;
private string m_fileext;
private string m_filepathname;
private string m_contenttype;
private string m_contentdisp;
private string m_typemime;
private string m_subtypemime;
private string m_contentstring;
private boolean m_ismissing;
public static final int saveas_auto = 0;
public static final int saveas_virtual = 1;
public static final int saveas_physical = 2;
file(){
m_startdata = 0;
m_enddata = 0;
m_size = 0;
m_fieldname = new string();
m_filename = new string();
m_fileext = new string();
m_filepathname = new string();
m_contenttype = new string();
m_contentdisp = new string();
m_typemime = new string();
m_subtypemime = new string();
m_contentstring = new string();
m_ismissing = true;
}
public void saveas(string s) throws ioexception, smartuploadexception{
saveas(s, 0);
}
public void saveas(string s, int i) throws ioexception, smartuploadexception{
string s1 = new string();
s1 = m_parent.getphysicalpath(s, i);
if(s1 == null)
throw new illegalargumentexception("there is no specified destination file (1140).");
try
{
java.io.file file = new java.io.file(s1);
fileoutputstream fileoutputstream = new fileoutputstream(file);
fileoutputstream.write(m_parent.m_binarray, m_startdata, m_size);
fileoutputstream.close();
}
catch(ioexception ioexception)
{
throw new smartuploadexception("file can't be saved (1120).");
}
}
public void filetofield(resultset resultset, string s) throws servletexception, ioexception, smartuploadexception, sqlexception{
long l = 0l;
int i = 0x10000;
int j = 0;
int k = m_startdata;
if(resultset == null)
throw new illegalargumentexception("the recordset cannot be null (1145).");
if(s == null)
throw new illegalargumentexception("the columnname cannot be null (1150).");
if(s.length() == 0)
throw new illegalargumentexception("the columnname cannot be empty (1155).");
l = biginteger.valueof(m_size).pide(biginteger.valueof(i)).longvalue();
j = biginteger.valueof(m_size).mod(biginteger.valueof(i)).intvalue();
try
{
for(int i1 = 1; (long)i1 < l; i1++)
{
resultset.updatebinarystream(s, new bytearrayinputstream(m_parent.m_binarray, k, i), i);
k = k != 0 ? k : 1;
k = i1 * i + m_startdata;
}
if(j > 0)
resultset.updatebinarystream(s, new bytearrayinputstream(m_parent.m_binarray, k, j), j);
}catch(sqlexception sqlexception){
byte abyte0[] = new byte[m_size];
system.arraycopy(m_parent.m_binarray, m_startdata, abyte0, 0, m_size);
resultset.updatebytes(s, abyte0);
}catch(exception exception)
{
throw new smartuploadexception("unable to save file in the database (1130).");
}
}
public boolean ismissing(){
return m_ismissing;
}
public string getfieldname(){
return m_fieldname;
}
public string getfilename(){
dateformat df = new simpledateformat("yyyymmddhhmmss");
string date = df.format(new date());
return date+m_filename;
}
public string getfilepathname(){
return m_filepathname;
}
public string getfileext(){
return m_fileext;
}
public string getcontenttype(){
return m_contenttype;
}
public string getcontentdisp(){
return m_contentdisp;
}
public string getcontentstring(){
string s = new string(m_parent.m_binarray, m_startdata, m_size);
return s;
}
public string gettypemime() throws ioexception{
return m_typemime;
}
public string getsubtypemime(){
return m_subtypemime;
}
public int getsize(){
return m_size;
}
protected int getstartdata(){
return m_startdata;
}
protected int getenddata(){
return m_enddata;
}
protected void setparent(smartupload smartupload){
m_parent = smartupload;
}
protected void setstartdata(int i){
m_startdata = i;
}
protected void setenddata(int i){
m_enddata = i;
}
protected void setsize(int i){
m_size = i;
}
protected void setismissing(boolean flag){
m_ismissing = flag;
}
protected void setfieldname(string s){
m_fieldname = s;
}
protected void setfilename(string s){
m_filename = s;
}
protected void setfilepathname(string s){
m_filepathname = s;
}
protected void setfileext(string s){
m_fileext = s;
}
protected void setcontenttype(string s){
m_contenttype = s;
}
protected void setcontentdisp(string s){
m_contentdisp = s;
}
protected void settypemime(string s){
m_typemime = s;
}
protected void setsubtypemime(string s){
m_subtypemime = s;
}
public byte getbinarydata(int i){
if(m_startdata + i > m_enddata)
throw new arrayindexoutofboundsexception("index out of range (1115).");
if(m_startdata + i <= m_enddata)
return m_parent.m_binarray[m_startdata + i];
else
return 0;
}
}
files类
/*
* 创建日期 2006-7-29
*
* 更改所生成文件模板为
* 窗口 > 首选项 > java > 代码生成 > 代码和注释
*/
package com.kinstar.issuing.file;
/**
* @author gongyifeng
*
* 更改所生成类型注释的模板为
* 窗口 > 首选项 > java > 代码生成 > 代码和注释
*/
import java.io.ioexception;
import java.util.*;
// referenced classes of package com.jspsmart.upload:
// file, smartupload
public class files{
private smartupload m_parent;
private hashtable m_files;
private int m_counter;
files(){
m_files = new hashtable();
m_counter = 0;
}
protected void addfile(file file){
if(file == null)
{
throw new illegalargumentexception("newfile cannot be null.");
} else {
m_files.put(new integer(m_counter), file);
m_counter++;
return;
}
}
public file getfile(int i)
{
if(i < 0)
throw new illegalargumentexception("file's index cannot be a negative value (1210).");
file file = (file)m_files.get(new integer(i));
if(file == null)
throw new illegalargumentexception("files' name is invalid or does not exist (1205).");
else
return file;
}
public int getcount()
{
return m_counter;
}
public long getsize() throws ioexception
{
long l = 0l;
for(int i = 0; i < m_counter; i++)
l += getfile(i).getsize();
return l;
}
public collection getcollection()
{
return m_files.values();
}
public enumeration getenumeration()
{
return m_files.elements();
}
}
request类
/*
* 创建日期 2006-7-29
*
* 更改所生成文件模板为
* 窗口 > 首选项 > java > 代码生成 > 代码和注释
*/
package com.kinstar.issuing.file;
/**
* @author gongyifeng
*
* 更改所生成类型注释的模板为
* 窗口 > 首选项 > java > 代码生成 > 代码和注释
*/
import java.util.enumeration;
import java.util.hashtable;
public class request
{
private hashtable m_parameters;
private int m_counter;
request(){
m_parameters = new hashtable();
m_counter = 0;
}
protected void putparameter(string s, string s1) {
if(s == null)
throw new illegalargumentexception("the name of an element cannot be null.");
if(m_parameters.containskey(s))
{
hashtable hashtable = (hashtable)m_parameters.get(s);
hashtable.put(new integer(hashtable.size()), s1);
} else{
hashtable hashtable1 = new hashtable();
hashtable1.put(new integer(0), s1);
m_parameters.put(s, hashtable1);
m_counter++;
}
}
public string getparameter(string s){
if(s == null)
throw new illegalargumentexception("form's name is invalid or does not exist (1305).");
hashtable hashtable = (hashtable)m_parameters.get(s);
if(hashtable == null)
return null;
else
return (string)hashtable.get(new integer(0));
}
public enumeration getparameternames()
{
return m_parameters.keys();
}
public string[] getparametervalues(string s)
{
if(s == null)
throw new illegalargumentexception("form's name is invalid or does not exist (1305).");
hashtable hashtable = (hashtable)m_parameters.get(s);
if(hashtable == null)
return null;
string as[] = new string[hashtable.size()];
for(int i = 0; i < hashtable.size(); i++)
as[i] = (string)hashtable.get(new integer(i));
return as;
}
}
smartupload类
/*
* 创建日期 2006-7-29
*
* 更改所生成文件模板为
* 窗口 > 首选项 > java > 代码生成 > 代码和注释
*/
package com.kinstar.issuing.file;
/**
* @author gongyifeng
*
* 更改所生成类型注释的模板为
* 窗口 > 首选项 > java > 代码生成 > 代码和注释
*/
import java.io.*;
import java.sql.resultset;
import java.sql.sqlexception;
import java.util.vector;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.jspwriter;
import javax.servlet.jsp.pagecontext;
// referenced classes of package com.jspsmart.upload:
// files, request, smartuploadexception, file
public class smartupload
{
protected byte m_binarray[];
protected httpservletrequest m_request;
protected httpservletresponse m_response;
protected servletcontext m_application;
private int m_totalbytes;
private int m_currentindex;
private int m_startdata;
private int m_enddata;
private string m_boundary;
private long m_totalmaxfilesize;
private long m_maxfilesize;
private vector m_deniedfileslist;
private vector m_allowedfileslist;
private boolean m_denyphysicalpath;
private boolean m_forcephysicalpath;
private string m_contentdisposition;
public static final int save_auto = 0;
public static final int save_virtual = 1;
public static final int save_physical = 2;
private files m_files;
private request m_formrequest;
public smartupload()
{
m_totalbytes = 0;
m_currentindex = 0;
m_startdata = 0;
m_enddata = 0;
m_boundary = new string();
m_totalmaxfilesize = 0l;
m_maxfilesize = 0l;
m_deniedfileslist = new vector();
m_allowedfileslist = new vector();
m_denyphysicalpath = false;
m_forcephysicalpath = false;
m_contentdisposition = new string();
m_files = new files();
m_formrequest = new request();
}
public final void init(servletconfig servletconfig) throws servletexception
{
m_application = servletconfig.getservletcontext();
}
public void service(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse)throws servletexception, ioexception
{
m_request = httpservletrequest;
m_response = httpservletresponse;
}
public final void initialize(servletconfig servletconfig, httpservletrequest httpservletrequest, httpservletresponse httpservletresponse)throws servletexception
{
m_application = servletconfig.getservletcontext();
m_request = httpservletrequest;
m_response = httpservletresponse;
}
public final void initialize(pagecontext pagecontext)throws servletexception
{
m_application = pagecontext.getservletcontext();
m_request = (httpservletrequest)pagecontext.getrequest();
m_response = (httpservletresponse)pagecontext.getresponse();
}
public final void initialize(servletcontext servletcontext, httpsession httpsession, httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, jspwriter jspwriter) throws servletexception
{
m_application = servletcontext;
m_request = httpservletrequest;
m_response = httpservletresponse;
}
public void upload()throws servletexception, ioexception, smartuploadexception
{
int i = 0;
boolean flag = false;
long l = 0l;
boolean flag1 = false;
string s = new string();
string s2 = new string();
string s4 = new string();
string s5 = new string();
string s6 = new string();
string s7 = new string();
string s8 = new string();
string s9 = new string();
string s10 = new string();
boolean flag2 = false;
m_totalbytes = m_request.getcontentlength();
m_binarray = new byte[m_totalbytes];
int j;
for(; i < m_totalbytes; i += j)
try
{
m_request.getinputstream();
j = m_request.getinputstream().read(m_binarray, i, m_totalbytes - i);
}
catch(exception exception)
{
throw new smartuploadexception("unable to upload.");
}
for(; !flag1 && m_currentindex < m_totalbytes; m_currentindex++)
if(m_binarray[m_currentindex] == 13)
flag1 = true;
else
m_boundary = m_boundary + (char)m_binarray[m_currentindex];
if(m_currentindex == 1)
return;
for(m_currentindex++; m_currentindex < m_totalbytes; m_currentindex = m_currentindex + 2)
{
string s1 = getdataheader();
m_currentindex = m_currentindex + 2;
boolean flag3 = s1.indexof("filename") > 0;
string s3 = 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))
throw new securityexception("the extension of the file is denied to be uploaded (1015).");
if(!m_allowedfileslist.isempty() && !m_allowedfileslist.contains(s5))
throw new securityexception("the extension of the file is not allowed to be uploaded (1010).");
if(m_maxfilesize > 0l && (long)((m_enddata - m_startdata) + 1) > m_maxfilesize)
throw new securityexception("size exceeded for this file : " + s4 + " (1105).");
l += (m_enddata - m_startdata) + 1;
if(m_totalmaxfilesize > 0l && l > m_totalmaxfilesize)
throw new securityexception("total file size exceeded (1110).");
}
if(flag3)
{
com.kinstar.issuing.file.file file = new com.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
{
string s11 = new string(m_binarray, m_startdata, (m_enddata - m_startdata) + 1);
m_formrequest.putparameter(s3, s11);
}
if((char)m_binarray[m_currentindex + 1] == '-')
break;
}
}
public int save(string s)throws servletexception, ioexception, smartuploadexception
{
return save(s, 0);
}
public int save(string s, int i)throws servletexception, ioexception, smartuploadexception
{
int j = 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(int k = 0; k < m_files.getcount(); k++)
if(!m_files.getfile(k).ismissing())
{
m_files.getfile(k).saveas(s + m_files.getfile(k).getfilename(), i);
j++;
}
return j;
}
public int getsize()
{
return m_totalbytes;
}
public byte getbinarydata(int i)
{
byte byte0;
try
{
byte0 = m_binarray[i];
}
catch(exception exception)
{
throw new arrayindexoutofboundsexception("index out of range (1005).");
}
return byte0;
}
public files getfiles()
{
return m_files;
}
public request getrequest()
{
return m_formrequest;
}
public void downloadfile(string s) throws servletexception, ioexception, smartuploadexception
{
downloadfile(s, null, null);
}
public void downloadfile(string s, string s1) throws servletexception, ioexception, smartuploadexception, smartuploadexception
{
downloadfile(s, s1, null);
}
public void downloadfile(string s, string s1, string s2)throws servletexception, ioexception, smartuploadexception
{
downloadfile(s, s1, s2, 65000);
}
public void downloadfile(string s, string s1, string s2, int i)throws servletexception, ioexception, smartuploadexception
{
if(s == null)
throw new illegalargumentexception("file '" + s + "' not found (1040).");
if(s.equals(""))
throw new illegalargumentexception("file '" + s + "' not found (1040).");
if(!isvirtual(s) && m_denyphysicalpath)
throw new securityexception("physical path is denied (1035).");
if(isvirtual(s))
s = m_application.getrealpath(s);
java.io.file file = new java.io.file(s);
fileinputstream fileinputstream = new fileinputstream(file);
long l = file.length();
boolean flag = false;
int k = 0;
byte abyte0[] = new byte[i];
if(s1 == null)
m_response.setcontenttype("application/x-msdownload");
else
if(s1.length() == 0)
m_response.setcontenttype("application/x-msdownload");
else
m_response.setcontenttype(s1);
m_response.setcontentlength((int)l);
m_contentdisposition = m_contentdisposition != null ? m_contentdisposition : "attachment;";
if(s2 == null)
m_response.setheader("content-disposition", m_contentdisposition + " filename=" + getfilename(s));
else
if(s2.length() == 0)
m_response.setheader("content-disposition", m_contentdisposition);
else
m_response.setheader("content-disposition", m_contentdisposition + " filename=" + s2);
while((long)k < l)
{
int j = fileinputstream.read(abyte0, 0, i);
k += j;
m_response.getoutputstream().write(abyte0, 0, j);
}
fileinputstream.close();
}
public void downloadfield(resultset resultset, string s, string s1, string s2) throws servletexception, ioexception, sqlexception
{
if(resultset == null)
throw new illegalargumentexception("the recordset cannot be null (1045).");
if(s == null)
throw new illegalargumentexception("the columnname cannot be null (1050).");
if(s.length() == 0)
throw new illegalargumentexception("the columnname cannot be empty (1055).");
byte abyte0[] = resultset.getbytes(s);
if(s1 == null)
m_response.setcontenttype("application/x-msdownload");
else
if(s1.length() == 0)
m_response.setcontenttype("application/x-msdownload");
else
m_response.setcontenttype(s1);
m_response.setcontentlength(abyte0.length);
if(s2 == null)
m_response.setheader("content-disposition", "attachment;");
else
if(s2.length() == 0)
m_response.setheader("content-disposition", "attachment;");
else
m_response.setheader("content-disposition", "attachment; filename=" + s2);
m_response.getoutputstream().write(abyte0, 0, abyte0.length);
}
public void fieldtofile(resultset resultset, string s, string s1)throws servletexception, ioexception, smartuploadexception, sqlexception
{
try
{
if(m_application.getrealpath(s1) != null)
s1 = m_application.getrealpath(s1);
inputstream inputstream = resultset.getbinarystream(s);
fileoutputstream fileoutputstream = new fileoutputstream(s1);
int i;
while((i = inputstream.read()) != -1)
fileoutputstream.write(i);
fileoutputstream.close();
}
catch(exception exception)
{
throw new smartuploadexception("unable to save file from the database (1020).");
}
}
private string getdatafieldvalue(string s, string s1)
{
string s2 = new string();
string s3 = new string();
int i = 0;
boolean flag = false;
boolean flag1 = false;
boolean flag2 = false;
s2 = s1 + "=" + '"';
i = s.indexof(s2);
if(i > 0)
{
int j = i + s2.length();
int k = j;
s2 = "\"";
int l = s.indexof(s2, j);
if(k > 0 && l > 0)
s3 = s.substring(k, l);
}
return s3;
}
private string getfileext(string s)
{
string s1 = new string();
int i = 0;
int j = 0;
if(s == null)
return null;
i = s.lastindexof(46) + 1;
j = s.length();
s1 = s.substring(i, j);
if(s.lastindexof(46) > 0)
return s1;
else
return "";
}
private string getcontenttype(string s)
{
string s1 = new string();
string s2 = new string();
int i = 0;
boolean flag = false;
s1 = "content-type:";
i = s.indexof(s1) + s1.length();
if(i != -1)
{
int j = s.length();
s2 = s.substring(i, j);
}
return s2;
}
private string gettypemime(string s)
{
string s1 = new string();
int i = 0;
i = s.indexof("/");
if(i != -1)
return s.substring(1, i);
else
return s;
}
private string getsubtypemime(string s)
{
string s1 = new string();
int i = 0;
boolean flag = false;
i = s.indexof("/") + 1;
if(i != -1)
{
int j = s.length();
return s.substring(i, j);
} else
{
return s;
}
}
private string getcontentdisp(string s)
{
string s1 = new string();
int i = 0;
int j = 0;
i = s.indexof(":") + 1;
j = s.indexof(";");
s1 = s.substring(i, j);
return s1;
}
private void getdatasection()
{
boolean flag = false;
string s = new string();
int i = m_currentindex;
int j = 0;
int k = m_boundary.length();
m_startdata = m_currentindex;
m_enddata = 0;
while(i < m_totalbytes)
if(m_binarray[i] == (byte)m_boundary.charat(j))
{
if(j == k - 1)
{
m_enddata = ((i - k) + 1) - 3;
break;
}
i++;
j++;
} else
{
i++;
j = 0;
}
m_currentindex = m_enddata + k + 3;
}
private string getdataheader()
{
int i = m_currentindex;
int j = 0;
boolean flag = false;
for(boolean flag1 = false; !flag1;)
if(m_binarray[m_currentindex] == 13 && m_binarray[m_currentindex + 2] == 13)
{
flag1 = true;
j = m_currentindex - 1;
m_currentindex = m_currentindex + 2;
} else
{
m_currentindex++;
}
string s = new string(m_binarray, i, (j - i) + 1);
return s;
}
private string getfilename(string s)
{
string s1 = new string();
string s2 = new string();
int i = 0;
boolean flag = false;
boolean flag1 = false;
boolean flag2 = false;
i = s.lastindexof(47);
if(i != -1)
return s.substring(i + 1, s.length());
i = s.lastindexof(92);
if(i != -1)
return s.substring(i + 1, s.length());
else
return s;
}
public void setdeniedfileslist(string s) throws servletexception, ioexception, sqlexception
{
string s1 = "";
if(s != null)
{
string s2 = "";
for(int i = 0; i < s.length(); i++)
if(s.charat(i) == ',')
{
if(!m_deniedfileslist.contains(s2))
m_deniedfileslist.addelement(s2);
s2 = "";
} else
{
s2 = s2 + s.charat(i);
}
if(s2 != "")
m_deniedfileslist.addelement(s2);
} else
{
m_deniedfileslist = null;
}
}
public void setallowedfileslist(string s)
{
string s1 = "";
if(s != null)
{
string s2 = "";
for(int i = 0; i < s.length(); i++)
if(s.charat(i) == ',')
{
if(!m_allowedfileslist.contains(s2))
m_allowedfileslist.addelement(s2);
s2 = "";
} else
{
s2 = s2 + s.charat(i);
}
if(s2 != "")
m_allowedfileslist.addelement(s2);
} else
{
m_allowedfileslist = null;
}
}
public void setdenyphysicalpath(boolean flag)
{
m_denyphysicalpath = flag;
}
public void setforcephysicalpath(boolean flag)
{
m_forcephysicalpath = flag;
}
public void setcontentdisposition(string s)
{
m_contentdisposition = s;
}
public void settotalmaxfilesize(long l)
{
m_totalmaxfilesize = l;
}
public void setmaxfilesize(long l)
{
m_maxfilesize = l;
}
protected string getphysicalpath(string s, int i)throws ioexception
{
string s1 = new string();
string s2 = new string();
string s3 = new string();
boolean flag = false;
s3 = system.getproperty("file.separator");
if(s == null)
throw new illegalargumentexception("there is no specified destination file (1140).");
if(s.equals(""))
throw new illegalargumentexception("there is no specified destination file (1140).");
if(s.lastindexof("\\") >= 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.file file = new java.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;
return s1;
}
if(flag)
{
if(m_denyphysicalpath)
throw new illegalargumentexception("physical path is denied (1125).");
else
return s;
} else
{
throw new illegalargumentexception("this path does not exist (1135).");
}
}
if(i == 1)
{
if(isvirtual(s1))
{
s1 = m_application.getrealpath(s1);
if(s1.endswith(s3))
s1 = s1 + s2;
else
s1 = s1 + s3 + s2;
return s1;
}
if(flag)
throw new illegalargumentexception("the path is not a virtual path.");
else
throw new illegalargumentexception("this path does not exist (1135).");
}
if(i == 2)
{
if(flag)
if(m_denyphysicalpath)
throw new illegalargumentexception("physical path is denied (1125).");
else
return s;
if(isvirtual(s1))
throw new illegalargumentexception("the path is not a physical path.");
else
throw new illegalargumentexception("this path does not exist (1135).");
} else
{
return null;
}
}
public void uploadinfile(string s)throws ioexception, smartuploadexception
{
int i = 0;
int j = 0;
boolean flag = false;
if(s == null)
throw new illegalargumentexception("there is no specified destination file (1025).");
if(s.length() == 0)
throw new illegalargumentexception("there is no specified destination file (1025).");
if(!isvirtual(s) && m_denyphysicalpath)
throw new securityexception("physical path is denied (1035).");
i = m_request.getcontentlength();
m_binarray = new byte[i];
int k;
for(; j < i; j += k)
try
{
k = m_request.getinputstream().read(m_binarray, j, i - j);
}
catch(exception exception)
{
throw new smartuploadexception("unable to upload.");
}
if(isvirtual(s))
s = m_application.getrealpath(s);
try
{
java.io.file file = new java.io.file(s);
fileoutputstream fileoutputstream = new fileoutputstream(file);
fileoutputstream.write(m_binarray);
fileoutputstream.close();
}
catch(exception exception1)
{
throw new smartuploadexception("the form cannot be saved in the specified file (1030).");
}
}
private boolean isvirtual(string s)
{
if(m_application.getrealpath(s) != null)
{
java.io.file file = new java.io.file(m_application.getrealpath(s));
return file.exists();
} else
{
return false;
}
}
}
smartuploadexception 类
/*
* 创建日期 2006-7-29
*
* 更改所生成文件模板为
* 窗口 > 首选项 > java > 代码生成 > 代码和注释
*/
package com.kinstar.issuing.file;
/**
* @author gongyifeng
*
* 更改所生成类型注释的模板为
* 窗口 > 首选项 > java > 代码生成 > 代码和注释
*/
public class smartuploadexception extends exception
{
smartuploadexception(string s)
{
super(s);
}
}
上传的servlet
package com.kinstar.issuing.action;
import java.io.ioexception;
import javax.servlet.servlet;
import javax.servlet.servletexception;
import java.io.*;
import java.sql.sqlexception;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import com.kinstar.issuing.file.file;
import com.kinstar.issuing.file.smartupload;
import com.kinstar.issuing.objects.t_user;
import com.kinstar.issuing.operation.useroperation;
import com.kinstar.issuing.program.programservice;
import com.kinstar.issuing.session.sessiongloble;
import com.kinstar.issuing.util.stringutil;
/**
* @version 1.0
* @author gyf
*/
public class upload2programaction extends httpservlet{
private servletconfig config;
/**
* 初始化servlet
*/
final public void init(servletconfig config) throws servletexception {
this.config = config;
}
/**
* 处理get请求
*/
public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
dopost(request,response);
}
/**
* 响应post请求
*/
public void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
int count=0;
smartupload mysmartupload = new smartupload();
try {
// 初始化
mysmartupload.initialize(config,request,response);
// 上载
mysmartupload.upload();
com.kinstar.issuing.file.file f1 = mysmartupload.getfiles().getfile(0);
// com.kinstar.issuing.file.file f2 = mysmartupload.getfiles().getfile(1);
string backpic = f1.getfilename();
//string name2 = f2.getfilename();
long size=0;
// 保存上载文件到指定目录
count=mysmartupload.save("ads");
response.sendredirect("program.jsp?dopass=ture");
}
catch (exception e){
response.sendredirect("fail.jsp");
}
}
2.common-fileupload组件
挺好用的,也能够上传大文件,我试过,300m以上的文件上传本地传非常快,异地测试也能够上传成功.
首先要下载org.apache.commons.fileupload包和org.apache.commons.io包
下面是我的servlet
package com.kinstar.issuing.action;
import java.io.ioexception;
import javax.servlet.servlet;
import javax.servlet.servletexception;
import java.io.*;
import java.sql.sqlexception;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.regex.*;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import org.apache.commons.fileupload.diskfileupload;
import org.apache.commons.fileupload.fileitem;
import org.apache.commons.fileupload.fileuploadexception;
import com.kinstar.issuing.objects.t_user;
import com.kinstar.issuing.operation.useroperation;
import com.kinstar.issuing.program.programservice;
import com.kinstar.issuing.session.sessiongloble;
import com.kinstar.issuing.util.stringutil;
/**
* @version 1.0
* @author gyf
*/
public class uploadprogramaction extends httpservlet{
private static final string content_type = "text/html; charset=gb2312";
/**
* 处理get请求
*/
public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
dopost(request,response);
}
/**
* 响应post请求
*/
public void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
// 变量定义
response.setcontenttype(content_type);
httpsession modifysession=request.getsession();
sessiongloble logonuser;
logonuser=(sessiongloble)modifysession.getattribute("userinfo");
if(logonuser==null){
response.sendredirect("mainindex.jsp");
}
t_user userinfo=new t_user();
useroperation user=null;
try {
user = new useroperation();
} catch (exception e1) {
// todo 自动生成 catch 块
e1.printstacktrace();
}
try {
userinfo=user.getuser(logonuser.getuserid());
} catch (exception e2) {
// todo 自动生成 catch 块
e2.printstacktrace();
}
//system.out.println("figure="+userinfo.getuserfigure());
printwriter out=response.getwriter();
dateformat updf = new simpledateformat("yyyymmddhhmm");
string updatetime = updf.format(new date());
int isneed = 0;
string ischeck="0";
//省农行用户上传的节目必需显示,且审批已经合格
if(userinfo.getuserfigure().equals("1")){
isneed = 1;
ischeck = "1";
}
else{
isneed = 0;
ischeck = "0";
}
int type=0;
string avatime="";
string screen="";
int filetime=0;
int filetimereal=0;
int circle=0;
string picswitch="";
string delestate="1";
string backpic="";
string fieldname="";
string finalname="";
string filenamereal="";
long size=0;
string name="";
try {
diskfileupload fu = new diskfileupload();
// 设置允许用户上传文件大小,单位:字节,这里设为2m
fu.setsizemax(5*1024*1024*1024);
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setsizethreshold(10*1024*1024);
// 设置一旦文件大小超过getsizethreshold()的值时数据存放在硬盘的目录
fu.setrepositorypath("c:\\windows\\temp\\");
//开始读取上传信息
list fileitems = fu.parserequest(request);
//依次处理每个上传的文件
iterator iter = fileitems.iterator();
//正则匹配,过滤路径取文件名
string regexp=".+\\\\(.+)$";
//过滤掉的文件类型
string[] errortype={".exe",".com",".cgi",".asp"};
pattern p = pattern.compile(regexp);
stringutil su = new stringutil();
while (iter.hasnext()) {
fileitem item = (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;
matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;temp<errortype.length;temp++){
if (m.group(1).endswith(errortype[temp])){
throw new ioexception(name+": wrong type");
}
}
dateformat df = new simpledateformat("yyyymmddhhmmss");
string date = df.format(new date());
filenamereal=date+m.group(1);
finalname=date+math.round(math.random()*10000)+filenamereal.substring(filenamereal.indexof("."));
//保存上传的文件到指定的目录
//在下文中上传文件至数据库时,将对这里改写
item.write(new file(getservletcontext().getrealpath(".//ads//")+finalname));
//out.print(finalname+size);
}
else
{
throw new ioexception("fail to upload");
}
}
if(item.isformfield()) {
// 获得表单域的名字
fieldname = item.getfieldname();
if(fieldname.equals("avatime"))
avatime=item.getstring();
if(fieldname.equals("screen"))
screen=item.getstring();
if(fieldname.equals("filetime"))
filetime = integer.parseint(item.getstring());
if(fieldname.equals("filetimereal"))
filetimereal = integer.parseint(item.getstring());
if(fieldname.equals("circle"))
circle = integer.parseint(item.getstring());
if(fieldname.equals("switchpic"))
picswitch = item.getstring();
}
}
}catch (ioexception e){
out.println(e);
}catch (fileuploadexception e){
out.println(e);
} catch (exception e) {
// todo 自动生成 catch 块
e.printstacktrace();
}
if(finalname.equals("")){
response.sendredirect("fail.jsp");
}
else{
try {
programservice ps = new programservice();
ps.insertprogram(userinfo.getuserid(),updatetime,type,finalname,size,isneed,avatime,delestate,ischeck,userinfo.getcity(),backpic,screen,filetime,filetimereal,picswitch,circle,userinfo.getuserfigure(),new string(filenamereal.getbytes("gb2312"),"iso8859-1"));
response.sendredirect("program.jsp?dopass=true");
} catch (exception e3) {
// todo 自动生成 catch 块
e3.printstacktrace();
}
}
}
}
以上就是java实现文件上传的代码实例的详细内容。