如果上传文件比较大或希望上传速度可以快一点可以考虑使用ftp上传和下载
实现ftp上传下载最主要的类就是FtpClient类,想了解详细信息可以查看对应的API。
一、ftp实现上传和下载
public class FtpUtils{
//定义ftp类
private FtpClient ftpClient;
//定义链接server的方法
public void connectToServer(String serverIp,int port,String userName,String pass,String path){
ftpClient = new FtpClient();
ftpClient.openServer(serverIp,port);//链接服务器
ftpClient.login(userName,pass); //登录
if(!StringUtils.isBlank(path))
ftpClient.cd(path);//切换到指定下载路径
ftpClient.binary();//指定使用2进制传输
}
public long upload(String fileName,String newFileName){
//定义结果>0表示成功,0表示上传的文件为空,-1表示文件不存在
long result = 0;
//定义FileInputStream读取本地文件
FileInputStream in= null;
//定义TelnetOutputStream写文件到服务器上
TelnetOutputStream out = null;
try{
File file = new File(fileName);
if(!file.exits())
return -1;
if(file.length()==0)
return 0;
in = new FileInputStream(file);
out = ftpClient.put(newFileName);
byte[] buffer = new byte[1024];
int length = 0;
while((length=in.read(buffer))>0){
out.write(buffer,0,length);
}catch(Exception e){
//打印日志
}finally{
//关闭io资源
}
return result;
}
}
public long download(String fileName,String newFileName){
//定义结果>0表示成功,0表示上传的文件为空,-1表示文件不存在
long result = 0;
//定义FileOutStream 写文件到本地
FileOutStream out= null;
//定义TelnetInputStream写文件到服务器上
TelnetInputStream in= null;
try{
File file = new File(newFileName);
in = ftpClient.get(fileName);
byte[] buffer = new byte[1024];
int length = 0;
while((length=in.read(buffer))>0){
out.write(buffer,0,length);
}catch(Exception e){
//打印日志
}finally{
//关闭io资源
}
return result;
}
}
}
http,ftp实现上传和下载(下)
猜你喜欢
转载自jameszhao1987.iteye.com/blog/1235479
今日推荐
周排行