62,614
社区成员
发帖
与我相关
我的任务
分享
/**
* Description: 向FTP服务器上传文件
* @Version1.0
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param path FTP服务器保存目录
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 返回上传状态 StatusCodes 成功与否
*/
public String uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
String error_age=StatusCodes.DownloadCompleted;
FTPClient ftp = new FTPClient();
try {
int reply;
logger.info(url+" "+port);
ftp.connect(url, port);//连接FTP服务器
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);//登录
ftp.setFileType(BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
ftp.setFileTransferMode( FTP.STREAM_TRANSFER_MODE);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
error_age=StatusCodes.ErrorOnUpload;
return error_age;
}
if(!ftp.changeWorkingDirectory(path))
{
File newFile = new File(path +"/"+ filename);
String dir = newFile.getParentFile().getPath();
if (!ftp.changeWorkingDirectory(dir)) {
if (!ftp.makeDirectory(newFile.getParentFile().getPath())) {
logger.debug("创建文件目录【" + dir + "】 失败!");
}
}
}
logger.info(path+"/"+filename);
ftp.storeFile(path+"/"+filename, input);
input.close();
ftp.logout();
error_age=StatusCodes.UploadCompleted;
} catch (IOException e) {
error_age=StatusCodes.ErrorOnUpload;
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
error_age=StatusCodes.ErrorOnUpload;
}
}
}
return error_age;
}