我出现这个问题的原因是:根目录下创建了两层目录,在windows上没有问题,但是在linux中,创建第二层目录时失败了。
出错时代码:
boolean saveldhtzp = FtpUtils.upload(systemType,
ftpHost,
Integer.valueOf(ftpPort),
ftpUser,
ftpPwd,
"ldhtzp/",
personInfoBean.getProjectId()+"/"+personInfoBean.getPersonId(),
new ByteArrayInputStream(file[i].getBytes()), personInfoBean.getPersonId()+picName+".jpg"); `
代码注释:ldhtzp是创建的根目录,personInfoBean.getProjectId()是创建的第一层目录,personInfoBean.getPersonId()是创建的第二层目录
解决问题:去掉第二层目录即可
修改后代码:
boolean saveldhtzp = FtpUtils.upload(systemType,
ftpHost, Integer.valueOf(ftpPort),
ftpUser,
ftpPwd,
"ldhtzp/",
personInfoBean.getProjectId(),
new ByteArrayInputStream(file[i].getBytes()), personInfoBean.getPersonId()+picName+".jpg");
下面是FtpUtils中upload方法代码
/**
* ftp上传单个文件
*
* @param ftpUrl
* ftp地址
* @param userName
* ftp的用户名
* @param password
* ftp的密码
* @param directory
* 上传至ftp的路径名不包括ftp地址
* @param is
* 要上传的文件流
* @param destName
* 上传至ftp后存储的文件名
* @throws IOException
*/
public static boolean upload(String systemType,String ftpUrl, int port, String userName, String password, String directory,
String newDirectory, InputStream is, String destName) throws IOException {
FTPClient ftpClient = new FTPClient();
boolean result = false;
try {
ftpClient.connect(ftpUrl, port);
boolean login = ftpClient.login(userName, password);
if(!login){
System.out.println("login"+login);
return login;
}
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
if("1".equals(systemType)){
ftpClient.enterLocalPassiveMode(); //linux系统注释掉
}
// 设置根目录
boolean changeWorkingDirectory = ftpClient.changeWorkingDirectory(directory);
if(!changeWorkingDirectory){
System.out.println("changeWorkingDirectory"+changeWorkingDirectory);
return changeWorkingDirectory;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("gbk");
// 创建新目录
ftpClient.makeDirectory(newDirectory);
// 设置上传目录
boolean changeWorkingDirectory2 = ftpClient.changeWorkingDirectory(newDirectory);
if(!changeWorkingDirectory2){
System.out.println("changeWorkingDirectory2"+changeWorkingDirectory2);
return changeWorkingDirectory2;
}
result = ftpClient.storeFile(destName, is);
return result;
} catch (NumberFormatException e) {
System.out.println("FTP端口配置错误:不是数字:");
throw e;
} catch (FileNotFoundException e) {
throw new FileNotFoundException();
} catch (IOException e) {
throw new IOException(e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
原因:linux环境中ftp只能一级一级的创建目录,不可一次创建多级目录,而windows环境中一次是可以创建多级目录的。