采用FTP协议实现文件的上传
请先明白一点,HTTP上传和FTP上传是不一样的,HTTP上传会带有头文件等等,你得分析,也就是通过网页上传。通过FTP上传不用,因为他不会带头文件,操作方式其实就和你在本地操作一个文件复制到另外一个地方没有什么区别,只是使用的类不一样而已。
下面是具体实现的原文件:
import java.io.File;import java.io.FileInputStream;import sun.net.TelnetOutputStream;import sun.net.ftp.FtpClient;/** *采用FTP协议实现多个文件的上传 *FTP协议是Internet上用来传送文件的协议,规定了Internet上文件互相传送的标准。在java中实 *现这一功能是借助FtpClient类完成的。具体实现过程:首先与FTP服务器建立连接;初始化文件的 *传输方式,包括ASCII和BINARY两种方式;将文件输出到文件输入流FileInputStream中; *FileInputStream中的数据读入字节数组中;字节数组中的数据写入输出流 *TelnetOutputStream(利用write方法将数据写入到一个网络链接上)。这样和源文件同名的一个 *文件就复制到了服务器端。本例的JavaBean中通过upload()方法完成文件上传过程。 */publicclass WriteFileToServer { public WriteFileToServer() { } publicstaticvoid main(String[] args) { WriteFileToServer writeFileToServer = new WriteFileToServer(); writeFileToServer.upload("C:\\eclipse.exe "); } publicstaticvoid upload(String localFileAndPath) { FtpClient ftpClient; try { ftpClient=new FtpClient("192.168.1.106",21); ftpClient.login("Anonymous","56553655@163.com"); /*********必须要有下面这一句,否则写入的大小与读入的大小不一致************/ ftpClient.binary(); /************************取得本地文件的属性**************************/ File f=new File(localFileAndPath); System.out.println("本地文件大小:"+f.length()); System.out.println("文件名:"+f.getName()); FileInputStream fis=new FileInputStream(new File(localFileAndPath)); //put方法的参数表示在FTP服务器上要生成的文件名 TelnetOutputStream tos=ftpClient.put(f.getName()); byte[] bt=newbyte[1024]; int len=0; int lenTotal=0; //采用循环的方式将从文件读入的流写到FTP服务器上 while((len=fis.read(bt))!=-1) { lenTotal+=len; tos.write(bt,0,len); } //System.out.println("写到服务器的大小:"+lenTotal); tos.close(); fis.close(); ftpClient.closeServer(); } catch (Exception e) { e.printStackTrace(); } }}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/fenglibing/archive/2007/10/09/1817349.aspx