What should I do if java ftp upload fails?
Recently I was working on a project that required uploading files to a designated directory via FTP. Then I found that the project could be successfully deployed on tomcat, but failed when deployed on weblogic. I found many reasons on the Internet and have not yet solved them.
boolean isSuccee = ftp.storeFile(fileName, in);
Here it keeps returning false and the upload fails
Then the solution online is to add ftp.enterLocalPassiveMode(); still does not solve the problem
Go directly to the code:
Connect to the ftp service first
private static FTPClient ftp; /* * 获得ftp链接 */ public static boolean connectFtp(Ftp ftpInfo) throws Exception { ftp = new FTPClient(); boolean flag = false; int reply; if(ftpInfo.getPort() != null && !"".equals(ftpInfo.getPort())){ ftp.connect(ftpInfo.getIpAddr(),ftpInfo.getPort()); }else{ ftp.connect(ftpInfo.getIpAddr()); } ftp.login(ftpInfo.getUserName(), ftpInfo.getPwd()); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return flag; } ftp.changeWorkingDirectory(ftpInfo.getPath()); flag = true; return flag; }
Then upload the file:
/** * 文件上传 * @param file * @throws IOException */ public static void uploadFile(File file) throws IOException { FileInputStream in = null; try { in = new FileInputStream(file); String fileName = file.getName(); /** * ftp.enterLocalPassiveMode(); * 这个方法的意思就是每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据。 * 为什么要这样做呢,因为ftp server可能每次开启不同的端口来传输数据, * 但是在linux上或者其他服务器上面,由于安全限制,可能某些端口没有开启,所以就出现阻塞。 */ ftp.enterLocalPassiveMode(); ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); boolean isSuccee = ftp.storeFile(fileName, in); int i = 1; String newFileName = null; while (!isSuccee) { //多次上传数据直到成功(最多12次) newFileName = i + fileName; isSuccee = ftp.storeFile(newFileName, in); i++; if(i>11){ break; } } String ftpPath = ServiceConstans.ONEPORT_FTP_PATH;//驳船配载图上传到FTP的路径 if (isSuccee ) { //成功 logger.info("FTP:文件上传成功!"); if( newFileName == null){ ftp.rename(fileName, ftpPath+fileName); // 第一次上传就成功 }else{ ftp.rename(newFileName, ftpPath+fileName); } } else { logger.info("FTP:文件上传失败!!"); throw new BusiException("FTP:文件上传失败!!"); } } catch (FileNotFoundException e) { logger.error("未找到相关文件!", e); } catch (IOException e) { logger.error("上传文件失败!", e); } finally { in.close(); //file.delete();//删除源文件 } }
Solution:
Since there is no problem with the code, check it from the server side ;
Because the version of the jar package on web logic is lower than the jar package in the project, if there is no forced setting to search for the jar package of this project, the jar package in weblogic will be loaded first, so the upload fails due to the version being too low.
##So add thejavalearning"
The above is the detailed content of What to do if java ftp upload fails. For more information, please follow other related articles on the PHP Chinese website!