Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kasundharmadasa/d6f097e8917d1d5f10de412f2e7c5fbf to your computer and use it in GitHub Desktop.
Save kasundharmadasa/d6f097e8917d1d5f10de412f2e7c5fbf to your computer and use it in GitHub Desktop.
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