急!!急!!急!! 如何用jsp实现FTP上传下载!!!!!! 上传到FTP的文件名和路径要如何得到??? 是不是需要先把文件传到 web服务器上 然后在上传到 FTP?
跪求各位达人.... 有源码最好... 分不够 再开贴送分!!!!
跪求各位达人.... 有源码最好... 分不够 再开贴送分!!!!
解决方案 »
- 定制hibernate save updata delete 的底层sql语句
- Spring 问题
- 问个弄过就会的问题
- 何取本机的windwos登入名和密码
- JSP如何向指向URL发送一个post请求,并获取返回值呢?
- 求救 !!!关于调用yahoo的API进行查询的问题 附源码和出错信息
- 请问大家在做jsp+javabean时调试的时候用什么工具比较好呢?
- 请大家帮我解决一下这个通过JDBC直连数据库的问题?
- 怎么用技术手段获取网络视频广告时长?
- active控件,发布的时候要把这个控件放在服务器的那个地方才行!!!
- jasperreport 打印打及印预览功能如何实现???
- 在weblogic,tomcat中怎样在互联网上访问非web目录下的文件
gujing01(巴洛克) 请问客户端具体要怎么实现拉?
doway(john) 我木有说清楚~~` 我要上传的文件是100M以上的文件 如果用这些组件的话 那速度方面....
各位大侠 帮帮小弟吧~~~~``
jspSmartUpload
http://www.knowsky.com/3136.html
http无法保持连接
如果你把SERVLET实现为FTPCLIENT,你很难进行大批量的文件传输.
我想大概应该用APPLET实现一个FTP客户端.我曾经实现过一个FTPCLIENT但是是桌面GUI,我没试过移植成APPLET,楼主可以试试哦~
我们最近做了一个简单的项目,是上传到数据库中,其实上传到文件夹中,更容易一些。
把我们的代码给你看看吧。
没有整理,可能你看起来会比较麻烦,不过仔细看看应该也可以明白吧。
使用的是MYSQL数据库。UploadFileServlet.javapackage gwsf;import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;public class UploadFileServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
final int NONE=0;
final int DATAHEADER=1;
final int FILEDATA=2;
final int FIELDDATA=3;
int totalbytes=request.getContentLength();
byte[]b = new byte[totalbytes];
String contentType=request.getContentType();
//System.out.println(contentType);
String fieldname="";
String fieldvalue="";
String filename="";
String boundary="";
String lastboundary="";
int fileSize=0;
Hashtable formfields=new Hashtable();
int pos=contentType.indexOf("boundary=");
String fileID;
if (pos!=-1)
{
pos+="boundary=".length();
boundary="--"+contentType.substring(pos);
lastboundary=boundary+"--";
} int state=NONE;
DataInputStream in = new DataInputStream(request.getInputStream());
in.readFully(b);
in.close();
FileOutputStream fileouttest;//
fileouttest = new FileOutputStream("c:\\test.txt");//
fileouttest.write(b);//
String reqcontent=new String(b);
BufferedReader reqbuf=new BufferedReader(new StringReader(reqcontent));
boolean flag=true;
int i=0;
while(flag==true)
{
String s=reqbuf.readLine();
if(s==lastboundary||s==null) break;
switch(state)
{
case NONE:
if (s.startsWith(boundary))
{
state = DATAHEADER;
i+=1;
}
break;
case DATAHEADER:
pos=s.indexOf("filename=");
if (pos==-1)
{
pos=s.indexOf("name=");
pos+="name=".length()+1;
s=s.substring(pos);
int l=s.length();
s=s.substring(0,l-1);
fieldname=s;
state=FIELDDATA;
}
else
{
String temp=s;
pos=s.indexOf("filename=");
//System.out.println(pos);
pos+="filename=".length()+1;
s=s.substring(pos);
int l=s.length();
s=s.substring(0,l-1);
pos=s.lastIndexOf("\\");
s=s.substring(pos+1);
filename=s;
pos=byteIndexOf(b,temp,0);
b=subBytes(b,pos+temp.getBytes().length+2,b.length);
s=reqbuf.readLine();
//File f= new File(filename);
//DataOutputStream fileout=new DataOutputStream(new FileOutputStream(f));
b=subBytes(b,s.getBytes().length+4,b.length);
pos=byteIndexOf(b,boundary,0);
b=subBytes(b,0,pos-1);
//fileout.write(b,0,b.length-1);
fileSize=b.length-1;
formfields.put("wjname",filename);
formfields.put("wjbytes",b);
state=FILEDATA;
}
break;
case FIELDDATA:
s=reqbuf.readLine();
fieldvalue=s;
formfields.put(fieldname,fieldvalue);
state=NONE;
break;
case FILEDATA:
if((!s.startsWith(boundary))&&(!s.startsWith(lastboundary)))
{
s=reqbuf.readLine();
if(s.startsWith(boundary))
{
state=DATAHEADER;
}
else break;
break;
}
}
}
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>文件上传结果</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H1>文件上传结果</H1><HR>");
out.println("类别为"+formfields.get("lb"));
out.println("文件名:"+formfields.get("wjname")+"已经上传!"+"文件长度为:"+fileSize+"字节");
//byte [] wjbyte=(byte [])formfields.get("wjbytes");
//String wj= new String(wjbyte);
//out.println("文件二进制数组为:"+wj);
out.println("发送单位:"+formfields.get("sjdw")+"收件用户:"+formfields.get("sjyh"));
out.println(formfields.get("bt"));
out.println(formfields.get("zhw"));
out.println("</BODY>");
out.println("</HTML>");
}
private static int byteIndexOf(byte[] b,String s,int start)
{
return byteIndexOf(b,s.getBytes(),start);
} private static int byteIndexOf(byte[] b,byte[]s,int start)
{
int i;
if(s.length==0)
{
return 0;
}
int max=b.length-s.length;
if(max<0)
return -1;
if (start>max)
return -1;
if(start<0)
start = 0;
search:
for (i=start;i<=max;i++)
{
if(b[i]==s[0])
{
int k=1;
while(k<s.length)
{
if(b[k+i]!=s[k])
{
continue search;
}
k++;
}
return i;
}
}
return -1;
}
private static byte[] subBytes(byte[] b,int from,int end)
{
byte[] result=new byte[end-from];
System.arraycopy(b,from,result,0,end-from);
return result;
} private static String subBytesString(byte[] b,int from,int end)
{
return new String(subBytes(b,from,end));
}}
import javax.servlet.http.*;
import java.io.*;
import java.util.*;public class TestUploadBean
{
private ServletContext application;
private HttpServletRequest request;
private HttpServletResponse response;
private int totalbytes ;
private byte[] b ;
private String boundary="";
private String lastboundary="";
private Hashtable formfields=new Hashtable();
private int pos; public TestUploadBean() {} public final void initialize(ServletConfig config,HttpServletRequest request,HttpServletResponse response) throws ServletException
{
application = config.getServletContext();
this.request = request;
this.response = response;
}
private void conBdy()
{
String contentType=request.getContentType(); ;
totalbytes=request.getContentLength();
b = new byte[totalbytes];
pos=contentType.indexOf("boundary=");
if (pos!=-1)
{
pos+="boundary=".length();
boundary="--"+contentType.substring(pos);
lastboundary=boundary+"--";
} } private void getDataByte()
{
try
{
DataInputStream in = new DataInputStream(request.getInputStream());
in.readFully(b);
in.close();
FileOutputStream fileouttest;//
fileouttest = new FileOutputStream("c:\\test.txt");//
fileouttest.write(b);// }
catch(Exception e)
{
System.out.println(" Unable to upload data .");
e.printStackTrace();
} } public void getData()
{
final int NONE=0;
final int DATAHEADER=1;
final int FILEDATA=2;
final int FIELDDATA=3;
String s=null;
boolean flag=true;
int state=NONE;
String fieldname="";
String fieldvalue="";
String filename="";
int fileSize=0;
conBdy();
getDataByte();
String reqcontent=new String(b);
BufferedReader reqbuf=new BufferedReader(new StringReader(reqcontent));
//int i=0;
while(flag==true)
{
try
{
s = reqbuf.readLine();
}
catch(Exception e)
{
System.out.println(" data is damaged.");
e.printStackTrace();
} if(s==lastboundary||s==null) break;
switch(state)
{
case NONE:
if (s.startsWith(boundary))
{
state = DATAHEADER;
//i+=1;
}
break;
case DATAHEADER:
pos=s.indexOf("filename=");
if (pos==-1)
{
pos=s.indexOf("name=");
pos+="name=".length()+1;
s=s.substring(pos);
int l=s.length();
s=s.substring(0,l-1);
fieldname=s;
state=FIELDDATA;
}
else
{
String temp=s;
pos=s.indexOf("filename=");
//System.out.println(pos);
pos+="filename=".length()+1;
s=s.substring(pos);
int l=s.length();
s=s.substring(0,l-1);
pos=s.lastIndexOf("\\");
s=s.substring(pos+1);
filename=s;
pos=byteIndexOf(b,temp,0);
b=subBytes(b,pos+temp.getBytes().length+2,b.length);
try
{
s = reqbuf.readLine();
}
catch(Exception e)
{
System.out.println(" data is damaged.");
e.printStackTrace();
} //File f= new File(filename);
//DataOutputStream fileout=new DataOutputStream(new FileOutputStream(f));
b=subBytes(b,s.getBytes().length+4,b.length);
pos=byteIndexOf(b,boundary,0);
b=subBytes(b,0,pos-1);
//fileout.write(b,0,b.length-1);
fileSize=b.length-1;
formfields.put("filename",filename);
formfields.put("filebytes",b);
formfields.put("filesize",Integer.toString(fileSize));
state=FILEDATA;
}
break;
case FIELDDATA:
try
{
s = reqbuf.readLine();
}
catch(Exception e)
{
System.out.println(" data is damaged.");
e.printStackTrace();
} fieldvalue=s;
formfields.put(fieldname,fieldvalue);
state=NONE;
break;
case FILEDATA:
if((!s.startsWith(boundary))&&(!s.startsWith(lastboundary)))
{
try
{
s = reqbuf.readLine();
}
catch(Exception e)
{
System.out.println(" data is damaged.");
e.printStackTrace();
}
if(s.startsWith(boundary))
{
state=DATAHEADER;
}
else break;
break;
}
}
} } private int byteIndexOf(byte[] b,String s,int start)
{
return byteIndexOf(b,s.getBytes(),start);
} private int byteIndexOf(byte[] b,byte[]s,int start)
{
int i;
if(s.length==0)
{
return 0;
}
int max=b.length-s.length;
if(max<0)
return -1;
if (start>max)
return -1;
if(start<0)
start = 0;
search:
for (i=start;i<=max;i++)
{
if(b[i]==s[0])
{
int k=1;
while(k<s.length)
{
if(b[k+i]!=s[k])
{
continue search;
}
k++;
}
return i;
}
}
return -1;
}
private byte[] subBytes(byte[] b,int from,int end)
{
byte[] result=new byte[end-from];
System.arraycopy(b,from,result,0,end-from);
return result;
} private String subBytesString(byte[] b,int from,int end)
{
return new String(subBytes(b,from,end));
} public String getFormfileds(String fieldsname)
{
return (String)formfields.get(fieldsname);
} public byte [] getFilebytes()
{
return (byte [])formfields.get("filebytes");
}
public String getFilename()
{
return (String)formfields.get("filename");
}}
我只是负责划分模块。这个是小组成员写的一个servlet 用来上传文件到数据库中。
我没有仔细看,应该是模仿SMARTDOWNLOAD写的吧。
如果有不明白的,可以继续在网上找,
有一本薄薄的《深入Java Servlet网络编程》清华2002年出的书里的第六章讲的比较详细,可以看看。
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import javax.swing.JProgressBar;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;import ecust.people4.exception.*;
import ecust.people4.demo.GeneralMetaInfo;
/**
* 批量上传客户端
* @author gujing
* @version 1.0
*/
class FtpClient
{
// private String cmd="";
/**
* 客户端SOCKET
*/
private Socket ftpclient=null;
/**
* 用于命令通道的格式化字符输出
*/
private PrintWriter out;
/**
* 用于命令通道的格式化字符输出
*/
private BufferedReader in;
/**
* 登陆的用户名
*/
private String loggedName;
/**
* 构造函数
* @throws Exception
*/
public FtpClient() throws Exception
{
}
/**
* 创建数据通道
* @param cmdstr 需要用数据通道通信的命令
* @return 数据通道SOCKET
* @throws Exception
*/
public Socket dataSocket(String cmdstr) throws Exception
{
ServerSocket dataserversocket=new ServerSocket(0);
PrintWriter out = new PrintWriter(ftpclient.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(ftpclient.getInputStream()));
String cmd="PORT ";
byte[] address=InetAddress.getLocalHost().getAddress();
//以下我没有按照标准FTP协议规定的写法
for(int i=0;i<address.length;i++)
{
// System.out.println(address[i]&0xff);
cmd+=address[i]&0xff;
// cmd+=",";
if(i==address.length-1)
{
cmd+=":";
}
else
{
cmd+=".";
}
}
cmd+=dataserversocket.getLocalPort();
cmd+="\r\n";
System.out.println(cmd);
out.write(cmd);
out.flush();
String response=in.readLine();//命令连接中,对PORT命令的响应
if(response.startsWith("425"))//PORT命令错误
{
System.out.println("PORT命令错误");
dataserversocket.close();
return null;
}
else if(response.startsWith("200"))//PORT命令正确
{
System.out.println("PORT命令正确");
}
out.write(cmdstr+"\r\n");
out.flush();
Socket datasocket=dataserversocket.accept();
dataserversocket.close();
return datasocket;
}
/**
* 处理LIST命令
* @return 从服务器端返回的文档/非文档列表,以MyProperty为元素的LIST,Label-NAME属性值,Value-ID
*/
public List doList()
{
try
{
Socket datasocket=this.dataSocket("LIST");
InputStream is=datasocket.getInputStream();
ObjectInputStream objectis=new ObjectInputStream(is);
List filelist=(List)objectis.readObject();
return filelist;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
/*
byte[] buffer1 = new byte[1024];
int size;
size=is.read(buffer1, 0, 1024);
System.out.println("受到长度"+size);
this.addToListFromByteArray(bufferlist,buffer1,size);
// System.out.write(buffer1, 0, size);
try
{
while (size==1024)
{
size=is.read(buffer1, 0, 1024);
this.addToListFromByteArray(bufferlist,buffer1,size);
// System.out.write(buffer1, 0, size);
}
}
catch(SocketException se)
{
se.printStackTrace();
}
datasocket.close();
resultbuffer=this.getbyteArrayFromByteList(bufferlist);
if(resultbuffer==null||resultbuffer.length==0)
{
return null;
}
else
{
return new String(resultbuffer,"GB2312");
}
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
*/
}
/**
* 处理ADDITIONATTRIBUTELIST命令,获取特有属性列表
* @param contenttype 要获取特有属性列表的CONTENTTYPE名
* @return 特有属性列表,从服务器端返回的特有属性列表,以MyAdditionAttribute为元素的LIST
*/
public List doAdditionAttributeList(String contenttype)
{
try
{
Socket datasocket=this.dataSocket("ADDITIONATTRIBUTELIST "+contenttype);
InputStream is=datasocket.getInputStream();
ObjectInputStream objectis=new ObjectInputStream(is);
List additionattributelist=(List)objectis.readObject();
return additionattributelist;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* 处理RIGHTRELATIONLIST命令,获取右边的关联类型
* @param contenttype 要获取右边的关联类型的CONTENTTYPE名
* @return 从服务器端返回的右边关联类型列表,以MyProperty为元素的LIST,Label-右边关联类型显示名,Value-右边关联类型标识
*/
public List doRightRelationList(String contenttype)
{
try
{
Socket datasocket=this.dataSocket("RIGHTRELATIONLIST "+contenttype);
InputStream is=datasocket.getInputStream();
ObjectInputStream objectis=new ObjectInputStream(is);
List rightrelationlist=(List)objectis.readObject();
return rightrelationlist;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* 处理RELATEDPUBLICOBJECTS命令,获取选中的关联类型右边所关联的实例列表
* @param relationname 要获取关联的实例列表的关联类型名
* @return 从服务器端返回的文档/非文档列表,以MyProperty为元素的LIST,Label-NAME属性值,Value-ID
*/
public List doRelatedPublicObjects(String relationname)
{
try
{
Socket datasocket=this.dataSocket("RELATEDPUBLICOBJECTS "+relationname);
InputStream is=datasocket.getInputStream();
ObjectInputStream objectis=new ObjectInputStream(is);
List relatedpublicobjects=(List)objectis.readObject();
return relatedpublicobjects;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* 处理CATEGORYLIST命令,获取特定CONTENTTYPE的类别列表
* @param contentype 要获取类别列表的CONTENTTYPE名
* @return 从服务器端返回的类别列表
*/
public List doCategoryList(String contentype)
{
try
{
Socket datasocket=this.dataSocket("CATEGORYLIST "+contentype);
InputStream is=datasocket.getInputStream();
ObjectInputStream objectis=new ObjectInputStream(is);
List categorylist=(List)objectis.readObject();
return categorylist;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* 判断是否是有预览类型
* @param contenttype 要判断的CONTENTTYPE
* @return
* @throws Exception
*/
public boolean doHaspreview(String contenttype) throws Exception
{
out.write("HASPREVIEW "+contenttype+"\r\n");
out.flush();
String response=in.readLine();
String value=response.substring(4);
if(value.equals("TRUE")) return true;
if(value.equals("FALSE")) return false;
//////////////////////////
return false;
}
* 批量上传
* @param contenttype CONTENTTYPE名
* @param folder 上传根文件夹
* @param configfile 元信息清单文件
* @param pbUpload 进度条
* @param mainframe 主窗口
* @return 错误个数
*/
public int doUpload(String contenttype,File folder,File configfile,JProgressBar pbUpload,MainFrame mainframe)
{
// String report="";
int errors=0;
Document document;
SAXReader saxReader = new SAXReader();
try
{
document = saxReader.read(configfile);
}
catch(Exception e)
{
// report+="清单文件不是有效的XML文件\r\n";
mainframe.log("清单文件不是有效的XML文件");
errors++;
e.printStackTrace();
// return report;
return errors;
}
try
{
Element rootelement=document.getRootElement();
List filepackagelist=rootelement.selectNodes("FILEPACKAGE");
if(filepackagelist.size()==0)
{
mainframe.log("至少需要一个FILEPACKAGE");
errors++;
// report+="至少需要一个FILEPACKAGE\r\n";
// return report;
return errors;
} System.out.println(filepackagelist.size());
Socket datasocket=this.dataSocket("STOR "+contenttype);
InputStream is=datasocket.getInputStream();
OutputStream os=datasocket.getOutputStream();
ObjectOutputStream objectos=new ObjectOutputStream(os);
out.write(".BEGIN\r\n");//传输文件起事标志
out.flush();
String =in.readLine();
if(==null||!.equals(".BEGIN_OK"))
{
System.out.println("传输文件同步错误");
mainframe.log("传输文件同步错误");
errors++;
// report+="传输文件同步错误\r\n";
datasocket.close();
// return report;
return errors;
}
mainframe.doUpdateProgressBar(pbUpload,filepackagelist.size(),true);
for(int i=0;i<filepackagelist.size();i++)
{
// 响应终止
try
{
if (Thread.interrupted())
{
throw new InterruptedException();
}
}
catch (InterruptedException e)
{
mainframe.log("文件传输被终止");
break;
}
//每一组逻辑相连的文件启事标志
out.write(".BEGIN_FILEPACKAGE\r\n");//传输FILEPACKAGE起事标志
out.flush();
=in.readLine();
if(==null||!.equals(".BEGIN_FILEPACKAGE_OK"))
{
System.out.println("PACKAGE文件同步错误");
mainframe.log("PACKAGE文件同步错误");
errors++;
// report+="PACKAGE文件同步错误\r\n";
datasocket.close();
// return report;
return errors;
}
Node filepackagenode=(Node)filepackagelist.get(i);
//发送元信息
GeneralMetaInfo gmi=GraphicUtil.fetchGeneralMetaInfoFromXML(filepackagenode);
objectos.writeObject(gmi);//序列化GMI
objectos.flush();
//发送额外属性信息
//如果发送对象null,则接受对象也为null
List additionattributes=GraphicUtil.fetchAdditionAttributeListFromXML(filepackagenode);
objectos.writeObject(additionattributes);
objectos.flush();
//发送关联信息
//如果发送对象null,则接受对象也为null
List relations=GraphicUtil.fetchRelationsFromXML(filepackagenode);
objectos.writeObject(relations);
objectos.flush();
//发送预蓝文件
String previewfilename=GraphicUtil.fetchPreviewName(filepackagenode);
objectos.writeObject(previewfilename);
objectos.flush();
if(previewfilename!=null)//预蓝文件
{
//发送文件内容流
File previewfile=new File(folder.getPath()+"/preview/"+previewfilename);
System.out.println(previewfile.getPath());
System.out.println(previewfile.length());
long filelength=previewfile.length();
objectos.writeLong(filelength);
objectos.flush();//发送文件大小
FileInputStream fis=new FileInputStream(previewfile);
byte[] buffer = new byte[1024];
int size;
while ((size = fis.read(buffer, 0, 1024)) != -1)
{
os.write(buffer, 0, size);
}
os.flush();
fis.close();
// 同步一下,这个同步是必须的,否则如果继续后面传诵,则后面的内容可能在服务器端被当成
//文件的一部分接受
String response=in.readLine();
System.out.println(response);
}
//发实际文件
List factfilenamelist=GraphicUtil.fetchFactFileNames(filepackagenode);
objectos.writeObject(factfilenamelist);
objectos.flush();
if(factfilenamelist!=null)
{
for(int j=0;j<factfilenamelist.size();j++)
{
// 发送文件内容流
String factfilename=factfilenamelist.get(j).toString();
File factfile=new File(folder.getPath(),factfilename);
System.out.println(factfile.getPath());
System.out.println(factfile.length());
long filelength=factfile.length();
objectos.writeLong(filelength);
objectos.flush();//发送文件大小
FileInputStream fis=new FileInputStream(factfile);
byte[] buffer = new byte[1024];
int size;
while ((size = fis.read(buffer, 0, 1024)) != -1)
{
os.write(buffer, 0, size);
}
os.flush();
fis.close();
//等待同步
String response=in.readLine();
System.out.println(response);
}
}
//发送FILEPACKAGE结束标志
out.write(".END_FILEPACKAGE\r\n");//传输FILEPACKAGE起事标志
out.flush();
String result="";
=in.readLine();
if(==null||!.startsWith(".END_FILEPACKAGE_OK"))
{
System.out.println("PACKAGE文件同步错误");
mainframe.log("PACKAGE文件同步错误");
errors++;
// report+="PACKAGE文件同步错误\r\n";
datasocket.close();
// return report;
return errors;
}
else
{
//report+=.substring(20);
result=.substring(20);
}
// System.out.println(report);
mainframe.log(result);
mainframe.doUpdateProgressBar(pbUpload,i+1,false);
}
out.write(".END\r\n");//传输结束
out.flush();
datasocket.close();
// return report;
return errors;
}
catch(Exception e)
{
e.printStackTrace();
mainframe.log("上传过程中出现严重系统错误");
errors++;
// return null;
return errors;
}
}
* 启动线程
*
*/
public void run()
{
synchronized(this.ftpclient)
{
try
{String cmd=null;
Socket datasocket=this.dataSocket(cmd);
InputStream is=datasocket.getInputStream();
OutputStream os=datasocket.getOutputStream();
if(cmd.equals("LIST"))
{
byte[] buffer2 = new byte[1024];
int size;
size=is.read(buffer2, 0, 1024);
System.out.write(buffer2, 0, size);
while (size==1024)
{
size=is.read(buffer2, 0, 1024);
System.out.write(buffer2, 0, size);
}
datasocket.close();
System.out.println("cccccccccccccccc");
}
if(cmd.startsWith("STOR"))//上传文件
{
out.write(".BEGIN\r\n");//传输文件起事标志
out.flush();
String =in.readLine();
if(!.equals(".BEGIN_OK"))
{
System.out.println("传输文件同步错误");
datasocket.close();
return;
}
File dir=new File("e:/testupload");
File files[]=dir.listFiles();
if(files!=null)
{
for(int i=0;i<files.length;i++)
{
// System.out.println(files[i].getName());
String filename=files[i].getName();
out.write(filename+"\r\n");
out.flush();//发送文件名
String response="";
response=in.readLine();
if(response.equals("FILENAME_OK"))//开始传数据
{
FileInputStream fis=new FileInputStream(files[i]);
byte[] buffer = new byte[1024];
int size;
while ((size = fis.read(buffer, 0, 1024)) != -1)
{
os.write(buffer, 0, size);
os.flush();
}
fis.close(); }
else
{
break;
}
}
//所有传输完毕
out.write(".END\r\n");
out.flush();//发送文件名
}
else
{
out.write(".END\r\n");
out.flush();//发送文件名
}
datasocket.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("LEAVE RUN");
}
}
/**
* CMSDK_USER命令
* @param username 用户名
* @return
* @throws Exception
*/
public boolean doUSER(String username) throws Exception
{
// 传用户名
String cmd="CMSDK_USER "+username+"\r\n";
out.write(cmd);
out.flush();
String response=in.readLine();
System.out.println(response);
if(!response.startsWith("331"))
{
System.out.println("用户名参数为空");
return false;
}
else
{
return true;
}
}
/**
* CMSDK_PASS命令
* @param password 密码
* @return
* @throws Exception
*/
public boolean doPASS(String password) throws FtpClientException,Exception
{
// //传密码
String cmd="CMSDK_PASS "+password+"\r\n";
out.write(cmd);
out.flush();
String response=in.readLine();
if(!response.startsWith("230"))
{
FtpClientException fce=new FtpClientException();
String errormsg;
String errorcode;
if(response.startsWith("500"))
{
System.out.println("密码参数为空");
errorcode="500";
errormsg="密码参数为空";
}
else if(response.startsWith("530"))
{
System.out.println("帐户或密码错误");
errorcode="530";
errormsg="帐户或密码错误";
}
else if(response.startsWith("540"))
{
System.out.println("帐户不处于有效状态");
errorcode="540";
errormsg="帐户不处于有效状态";
}
else
{
System.out.println("不明的错误");
errorcode="999";
errormsg="不明的错误";
}
fce.setErrorcode(errorcode);
fce.setErrormessage(errormsg);
ftpclient.close();
return false;
}
else
{
System.out.println(response);
loggedName=response.substring(4);
return true;
}
}
/**
* 连接服务器
* @param ip
* @param port
* @return
*/
public boolean doConnect(String ip,int port)
{
try
{
this.ftpclient=new Socket(ip,port);
in= new BufferedReader(new InputStreamReader(ftpclient.getInputStream()));
this.out= new PrintWriter(ftpclient.getOutputStream(),true);
System.out.println(in.readLine());
return true;
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}
/**
* 断开服务器
* @return
*/
public void doDisconnect()
{
out.write("DISCONNECT\r\n");
out.flush();
try
{
if(in.readLine().equals("DISCONNECT_OK"))
{
ftpclient.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* 改变当前CONTENTTYPE
* @param contenttype 要改变为的CONTENTTYPE
* @return
*/
public boolean doCWD(String contenttype)
{
try
{
out.write("CWD "+contenttype+"\r\n");
out.flush();
String response=in.readLine();
if(response==null)
{
return false;
}
else if(response.startsWith("200"))
{
return true;
}
else
{
return false;
}
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}
/**
* 获取登陆名
* @return
*/
public String getLoggedName() {
return loggedName;
}
/**
* 获取CONTENTTYPE列表
* @return 以;分隔的字符串
*/
public String getContenttypeList()
{
try
{
String response=in.readLine();
if(response==null||response.equals(""))
{
return null;
}
else
{
return response;
}
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
/* public void addToListFromByteArray(List list,byte [] bytearray,int size)
{
if(bytearray==null||bytearray.length==0)
{
return;
}
for(int i=0;i<bytearray.length&&i<size;i++)
{
list.add(new Byte(bytearray[i]));
}
}*/
/* public byte[] getbyteArrayFromByteList(List list)
{
if(list==null||list.size()==0)
{
return null;
}
byte result[]=new byte[list.size()];
for(int i=0;i<list.size();i++)
{
result[i]=((Byte)list.get(i)).byteValue();
}
return result;
}*/
}
上面是我们项目里要用到的类似FTPCLIENT的非标准的实现,这个实现中用的通信协议不是标准的FTP,并且与业务偶合紧密。(我们不需要标准FTP协议因为FTPSERVER也是自己做的),楼主你需要去了解FTP协议,然后用类似的方法去实现。