上传文件
<form METHOD="POST" ACTION="tt.jsp" ENCTYPE="multipart/form-data">
<input TYPE="FILE" NAME="FILE1" SIZE="50">
<input TYPE="SUBMIT" VALUE="Upload">
</form>
<%
try{
Upload load=new Upload();
load.setDir("d:\\tt\\");
load.doUpload(request,response);
}
catch( Exception e ){
return;
}
%>
OK!
*
【使用例】
*
try {
*
Upload load=new Upload();
*
load.setDir("i:\\ztytest\\");
*
load.doUpload(req,res);
*
}
*
catch( Exception e ) {
*
return;
*
}
*/
public class Upload extends HttpServlet {
public String strDir;
public Upload()
{
}
public void doUpload(HttpServletRequest req, HttpServletResponse res)
throws IOException
{
String boundary=req.getHeader("Content-Type");
int pos=boundary.indexOf('=');
boundary=boundary.substring(pos+1);
boundary="--"+ boundary;
ServletInputStream in=req.getInputStream() ;
byte[] bytes=new byte[512];
int state=0;
ByteArrayOutputStream buffer=new ByteArrayOutputStream();
String name=null;
String value=null;
String filename=null;
String contentType=null;
int i=in.readLine(bytes,0,512);
while (-1!=i)
{
String st=new String(bytes,0,i);
if (st.startsWith(boundary))
{
state=0;
System.out.println(filename);
if (null!=name)
{
if(buffer.size()>2)
{
FileOutputStream outStream = new FileOutputStream(strDir+filename);
outStream.write(buffer.toByteArray(), 0, buffer.toByteArray().length);
outStream.close();
}
name=null;
value=null;
filename=null;
contentType=null;
buffer=new ByteArrayOutputStream();
}
}//end of st.startsWith(boundary)
else if (st.startsWith("Content-Disposition: form-data") && state==0)
{
StringTokenizer tokenizer=new StringTokenizer(st,";=\"");
while(tokenizer.hasMoreTokens())
{
String token=tokenizer.nextToken();
if(token.trim().startsWith("name"))
{
name=tokenizer.nextToken();
state=2;
}
else if(token.trim().startsWith("filename"))
{
filename=tokenizer.nextToken();
StringTokenizer ftokenizer=new StringTokenizer(filename,"\\");
filename=ftokenizer.nextToken();
while(ftokenizer.hasMoreTokens())
filename=ftokenizer.nextToken();
state=1;
break;
}
}
}//end state=0
else if (st.startsWith("Content-Type") && state==1)
{
pos=st.indexOf(":");
contentType=st.substring(pos+2,st.length()-2);
}//end state=1
else if (state==1)
state=3;
else if (st.equals("\r\n")&&state==2)
state=4;
else if (state==3)
buffer.write(bytes,0,i);
else if (state==4)
value=value==null?st:value+st;
i=in.readLine(bytes,0,512);
}//end while
}
public void setDir(String strSavePath)
{
strDir =strSavePath;
}
} </td>
<td width="186" valign="top" class="ArticleTeitle">
</td>
</tr>
<tr>
<td height="25" colspan="2" valign="top" class="ArticleTeitle">
↑返回目录
前一篇: 一行代码的程序
后一篇: 利用套接字在两人之间传文件