Created
October 17, 2018 09:37
-
-
Save kasundharmadasa/d6f097e8917d1d5f10de412f2e7c5fbf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void uploadToFTP(MultipartFile file, String baseDirectory, String scanDirectory) | |
throws ScanManagerException { | |
FTPClient client = new FTPClient(); | |
FileInputStream fis = null; | |
try { | |
client.connect("host","port"); | |
client.login("username","password"); | |
if (client.isConnected()) { | |
boolean directoryExists = client.changeWorkingDirectory(baseDirectory + File.separator + | |
scanDirectory); | |
if (!directoryExists) { | |
client.makeDirectory(baseDirectory + File.separator + scanDirectory); | |
client.changeWorkingDirectory(baseDirectory + File.separator + scanDirectory); | |
} | |
// Create an InputStream of the file to be uploaded | |
fis = (FileInputStream) file.getInputStream(); | |
client.setFileType(FTPClient.BINARY_FILE_TYPE); | |
// Store file to FTP server | |
client.storeFile(file.getOriginalFilename(), fis); | |
} else { | |
throw new ScanManagerException("Unable to connect to the FTP server"); | |
} | |
} catch (IOException e) { | |
throw new ScanManagerException("Error occurred while uploading the file " + | |
file.getOriginalFilename() + " to FTP server", e); | |
} finally { | |
try { | |
if (fis != null) { | |
fis.close(); | |
} | |
client.logout(); | |
client.disconnect(); | |
} catch (IOException e) { | |
logger.error("Error occurred while closing the connection to the FTP host"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment