/**
* 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;
}