java上传文件到ftp服务器_java上传文件到FTP服务器

/**

* 1、从磁盘读取相对应的文件

* 2、从配置文件读取connect信息

*/

//1

File file =new File(tempPath+"\\"+fileLoad.getFilename());

FileInputStream in=new FileInputStream(file);

//2

String ip=Config.getProperty("IP");

int port=Integer.parseInt(Config.getProperty("PORT"));

String username=Config.getProperty("USERNAME");

String password=Config.getProperty("PASSWORD");

String pa=Config.getProperty("PATH","utf-8");

//防止中文路径乱码的情况 ,properties默认为ISO-8859-1,如果存在用外部编辑器保存为GBK格式的中文,需要转换成GBK,否则路径乱码上传失败

String path=new String(pa.getBytes("ISO-8859-1"),"gbk");

//上传路径为配置文件配置的文件路径,与数据库的发送文件加路径组合而成,

System.out.println("上传的路径为:"+path+uploadPath);

//调用connet方法链接FTP服务器

connect(ip, port, username,password,path+uploadPath,fileLoad.getFilename(),in);

/**

* @param connect 使用apache FTPcliint上传文件至FTP服务器

* @param path 上传到ftp服务器哪个路径下   // FTP://192.168.0.8/产品盘/RC盘/万向财务/2015/8/erp_20150804/

* @param addr 地址     //FTP://192.168.0.8/

* @param port 端口号   //21

* @param username 用户名     //PFMRC

* @param password 密码  //7nwW@C

* @param filename 上传的文件名称

* @param input   输入流

* @return boolean 上传成功或者失败的结果

* @throws Exception

*/

public boolean connect(String address,int port,String username,String password, String path,String filename, InputStream input) throws Exception {

//初始化FTP服务器链接

boolean result=false;

FTPClient ftp= new FTPClient();

try {

int reply;      //定义变量,用来测试FTP服务器链接是否链接成功

ftp.connect(address,port);   //创建FTP链接

ftp.login(username,password);//登录

/*

* 如果reply为空,关闭链接,返回false

* */

reply = ftp.getReplyCode();

if (!FTPReply.isPositiveCompletion(reply)) {

ftp.disconnect();

return false;

}

//更换FTP的工作路径,并解决中文路径无法识别的问题,设置编码为ISO-8859-1,和java默认编码保持一致

boolean flag=ftp.changeWorkingDirectory(new String(path.getBytes(),"ISO-8859-1"));

ftp.setFileType(FTP.BINARY_FILE_TYPE);  //设置上传文件的类型,防止乱码

result=ftp.storeFile(filename, input);   //上传文件

System.out.println("上传的结果:"+result);

input.close(); //关闭输入流

ftp.logout(); //退出登录

} catch (IOException e) {

e.printStackTrace();

} finally {

if (ftp.isConnected()) {

try {

ftp.disconnect();

} catch (IOException ioe) {

}

}

}

return result;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值