import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Properties; /** * FTP file upload and download operations * * Created on December 19, 2017 17:49:02 * @author lilongsheng * @since 1.0 */ public final class FtpUtil { private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class); public static final Properties CONFIG = getConfigProperties(); public static final String PROTOCAL= "ftp://"; public static final String REMOTE_ADDRESS = CONFIG.getProperty("ftp.sqyc.host"); public static final String REMOTE_PATH = CONFIG.getProperty("ftp.sqyc.remotePath"); public static final String REMOTE_PORT = CONFIG.getProperty("ftp.sqyc.port"); private static final String PASSWORD = CONFIG.getProperty("ftp.sqyc.password"); private static final String USER_NAME = CONFIG.getProperty("ftp.sqyc.name"); private static Properties ftpPathConfig; private FTPClient ftpClient; private FtpUtil() { } public static FtpUtil getInstance() { return new FtpUtil(); } public static Properties getConfigProperties() { if(CONFIG == null){ Properties p = new Properties(); try { p.load(FtpUtil.class.getResourceAsStream("/ftp.properties")); return p ; } catch (IOException e) { e.printStackTrace (); logger.error("Risk control-upload and download exception-load configuration file error:{}",e.getMessage()); return null; } }else{ return CONFIG; } } /** * Connect to FTP server * @param remotePath remote access path */ public void connectServer(String remotePath) { String path=remotePath; try { if (path == null) { path = FtpUtil.REMOTE_PATH; } ftpClient = new FTPClient(); if (REMOTE_PORT == null || 0 == Integer.parseInt(REMOTE_PORT)) { ftpClient.connect(REMOTE_ADDRESS); } else { ftpClient.connect(REMOTE_ADDRESS, Integer.parseInt(REMOTE_PORT)); } int reply = ftpClient.getReplyCode (); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); // FTP server refused connection. closeConnect(); System.exit(1); } ftpClient.login(USER_NAME, PASSWORD); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // login success !!! if (path.length() != 0) { // boolean flag = createDirecroty(path, ftpClient); /*if (flag) { // set working directory successful !!! }*/ } } catch (IOException e) { // not login !!! e.printStackTrace (); } } public void connectServer() { connectServer(null); } /** * Close the connection to the FTP server */ public void closeConnect() { try { ftpClient.disconnect(); // disconnect success !!! } catch (IOException e) { // not disconnect !!! e.printStackTrace (); } } /** * Create a working directory and locate the current working directory to the newly created directory * Create a folder with one command, compatible with IBM FTP * @param path directory path to create * @return whether the operation was successful * @throws java.io.IOException */ public boolean alertWorkingDirectory(String path) throws IOException { boolean flag = ftpClient.changeWorkingDirectory(path); if (!flag) { String[] ps = path.split("/"); for (String p : ps) { if (!ftpClient.changeWorkingDirectory(p)) { if (ftpClient.makeDirectory(p)) { flag = ftpClient.changeWorkingDirectory(p); } else { flag = false; break; } } } } return flag; } /** * Description: recursively create remote server directory * * @param remote * Absolute path to remote server file * @param ftpClient * FTPClient object * @return boolean whether the directory creation was successful * @throws java.io.IOException */ public boolean createDirecroty(String remote, FTPClient ftpClient) throws IOException { boolean status = false; String directory = remote.substring(0, remote.lastIndexOf("/") + 1); if (!directory.equalsIgnoreCase("/") && !ftpClient.changeWorkingDirectory(new String(directory .getBytes("utf-8"), "iso-8859-1"))) { // If the remote directory does not exist, recursively create the remote server directory int start; int end; if (directory.startsWith("/")) { start = 1; } else { start = 0; } end = directory.indexOf("/", start); while (true) { String subDirectory = new String(remote.substring(start, end) .getBytes("utf-8"), "iso-8859-1"); if (!ftpClient.changeWorkingDirectory(subDirectory)) { if (ftpClient.makeDirectory(subDirectory)) { ftpClient.changeWorkingDirectory(subDirectory); } else { // Failed to create directory return status; } } start = end + 1; end = directory.indexOf("/", start); // Check if all directories are created if (end <= start) { break; } } } status = true; return status; } /** * File Upload * @param path file save path * @param fileName file name * @param inputStream file stream * @return whether the operation was successful */ public boolean upload(String path, String fileName, InputStream inputStream) { boolean flag = false; try { createDirecroty(path, ftpClient); flag = ftpClient.storeFile(fileName, inputStream); /*if (flag) { // upload success !!! }*/ } catch (IOException e) { // not upload !!! e.printStackTrace (); } return flag; } /** * Create an output stream based on the incoming path * @Version1.0 2014-7-9 at 11:55:14 am by Zhang Yanwei ([email protected]) * @param path file save path * @param fileName file name * @return */ public OutputStream storeFileStream(String path, String fileName) { OutputStream os = null; try { createDirecroty(path, ftpClient); os = ftpClient.storeFileStream(fileName); } catch (IOException e) { e.printStackTrace (); } return os; } /** * Check if the file exists * @param path file path * @param fileName file name * @return true: exists false: does not exist */ public boolean isFileExist(String path, String fileName){ try { boolean cdStatus = ftpClient.changeWorkingDirectory(new String(path.getBytes("utf-8"), "iso-8859-1")); if(!cdStatus){ return false; }else { String[] fileNames = ftpClient.listNames(); return Arrays.binarySearch(fileNames, fileName) > -1; } } catch (Exception e) { e.printStackTrace (); logger.error("Risk control - upload and download exception - whether the file exists error:{}",e.getMessage()); return false; } } /** * document dowload * @param fileName full path to file * @return downloaded file stream */ public InputStream download(String fileName) { InputStream inputStream = null; try { inputStream = ftpClient.retrieveFileStream(fileName); } catch (IOException e) { // not download !!! e.printStackTrace (); } return inputStream; } /** * Description: Get the file storage directory on the FTP server * * @param type * The module type to which the file belongs * @return file server-side path */ public static String getRemoteFileDir(int type){ StringBuilder remoteFileDir = new StringBuilder(); remoteFileDir.append(getFtpPathConfig().getProperty(String.valueOf(type))); SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd"); String datePath = sf.format(new Date()); remoteFileDir.append(datePath).append("/"); return remoteFileDir.toString(); } private static Properties getFtpPathConfig(){ synchronized (FtpUtil.class) { if (ftpPathConfig == null) { Properties p = new Properties(); InputStream in = null; try { in = FtpUtil.class.getResourceAsStream("/ftpUploadPathConfig.properties"); p.load(in); } catch (IOException e) { e.printStackTrace (); logger.error("Risk control-upload and download exception-file path configuration error:{}",e.getMessage()); }finally{ if(in != null){ try { in.close(); } catch (IOException e) { in = null; } } } ftpPathConfig = p; } } return ftpPathConfig; } public boolean completePendingCommand(){ try { return ftpClient.completePendingCommand(); } catch (IOException e) { e.printStackTrace (); logger.error("Risk control-upload and download exception-execute command error:{}",e.getMessage()); return false; } } }
Instructions:
FtpUtil ftpUtil = FtpUtil.getInstance(); try { String extension = FilenameUtils.getExtension(uploadFile.getOriginalFilename()); String uuid = UUID.randomUUID().toString(); String timeStamp = System.currentTimeMillis() + ""; String filePathDir = getRemoteFileDir(); //Start upload ftpUtil.connectServer(); boolean uploadFlag = ftpUtil.upload(filePathDir, uuid + "_" + timeStamp + "." + extension, uploadFile.getInputStream()); if (uploadFlag){ ok = true; absoluteUrl = FtpUtils.getFtpServerUrl() + filePathDir + uuid + "_" + timeStamp + "." + extension; oppositeUrl = filePathDir + uuid + "_" + timeStamp + "." + extension; logger.info("Upload order attachment-absoluteUrl:{" + absoluteUrl + "},oppositeUrl:{" + oppositeUrl + "}"); } } catch (Exception e) { e.printStackTrace (); logger.error("Upload order attachment - exception error:{"+e.getMessage() +"}"); }finally { ftpUtil.closeConnect(); }