JavaBean实现多文件上传(2)
Upload()方法的实现流程是:首先将输入流文件输出到字节数组m_binArray中,通过下面的代码实现。
m_totalBytes=1024;totalRead=0;
for(; totalRead < m_totalBytes; totalRead += readBytes)
try
{
m_request.getInputStream();
readBytes = m_request.getInputStream().read(m_binArray, totalRead, m_totalBytes - totalRead);
}catch(Exception e){ throw new SmartUploadException("Unable to upload.");}
这里采用了循环中多字节读取方法,以上循环不断地读取数据直到数组填满为止。如果一个文件可以完全得到,则文件的所有字节也就可以全部得到。但是因为网络速度通常比CPU慢得多,所以程序很容易在所有的数据到来之前就清空网络缓冲区。实际上,多字节读取方法在试图从暂时为空但是开放的网络缓存区读取数据时,该方法会返回0,这表示没有数据存在但网络流没有关闭。这种情况下,单字节方法将阻止运行程序的执行,所以多字节的行为优于单字节read()方法的行为。接下来将分析字节数组m_binArray。首先找到分隔符;使用getDataHeader()方法返回文件信息头的值,从中确定源文件的完整路径名、源文件的扩展名和源文件文件内容格式;使用getDataSection()方法返回文件的内容数据,并记录文件数据在字节数组中的起止位置。然后生成一个File类实例,并将文件的完整路径名、源文件的扩展名、源文件文件内容格式和文件的内容数据的起止位置放到File类实例的属性中。找到下一个分隔符,继续重复上述过程,直至分析完毕。
2、采用FTP协议实现多个文件的上传
FTP协议是Internet上用来传送文件的协议,规定了Internet上文件互相传送的标准。在java中实现这一功能是借助FtpClient类完成的。具体实现过程:首先与FTP服务器建立连接;初始化文件的传输方式,包括ASCII和BINARY两种方式;将文件输出到文件输入流FileInputStream中;FileInputStream中的数据读入字节数组中;字节数组中的数据写入输出流TelnetOutputStream(利用write方法将数据写入到一个网络链接上)。这样和源文件同名的一个文件就复制到了服务器端。本例的JavaBean中通过connectServer()、upload()和closeConnect()三个方法完成文件上传过程。主要实现如下:
public class ftpUpload
{
String filename;String filename1;FtpClient ftpClient;
public void connectServer(string server,string user,string password,string path)
{
//server:FTP服务器的IP地址;user:登录FTP服务器的用户名
//password:登录FTP服务器的用户名的口令;path:FTP服务器上的路径
try{
ftpClient=new FtpClient();
ftpClient.openServer(server);
ftpClient.login(user, password);
System.out.println("login success!");
if (path.length()!=0) ftpClient.cd(path);
ftpClient.binary();
}catch (IOException ex)
{
System.out.println(ex);
}
}
public void closeConnect()
{
try{
ftpClient.closeServer();
}catch (IOException ex) {System.out.println(ex);}
}
public void upload()
{
filename1=findFileName(filename);
//从filename中分析出文件的名称,作为目标文件的名称,具体方法实现未给出
try {
TelnetOutputStream os=ftpClient.put(filename1);
java.io.File file_in=new java.io.File(filename);
FileInputStream is=new FileInputStream(file_in);
byte[] bytes=new byte[1024];
int c;
while ((c=is.read(bytes))!=-1){ os.write(bytes,0,c); }
is.close(); os.close();
} catch (IOException ex) {System.out.println(ex);}
}
}