|
@@ -0,0 +1,63 @@
|
|
|
+package com.management.platform.util;
|
|
|
+import java.io.File;
|
|
|
+import java.io.FileInputStream;
|
|
|
+import java.io.IOException;
|
|
|
+import com.jcraft.jsch.ChannelSftp;
|
|
|
+import com.jcraft.jsch.JSch;
|
|
|
+import com.jcraft.jsch.Session;
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+@Component
|
|
|
+public class SFTPUploader {
|
|
|
+ @Value("${sftp.isEnabled}")
|
|
|
+ private boolean isEnabled;
|
|
|
+ @Value("${sftp.server}")
|
|
|
+ private String server;
|
|
|
+
|
|
|
+ @Value("${sftp.port}")
|
|
|
+ private int port;
|
|
|
+ @Value("${sftp.remoteDir}")
|
|
|
+ private String remoteDir;
|
|
|
+
|
|
|
+ @Value("${sftp.user}")
|
|
|
+ private String user;
|
|
|
+
|
|
|
+ @Value("${sftp.password}")
|
|
|
+ private String password;
|
|
|
+
|
|
|
+ public void uploadFile(File file) throws Exception {
|
|
|
+ if (!isEnabled) {
|
|
|
+ System.out.println("sftp is not enabled, please set sftp.isEnabled=true in application.properties");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ JSch jsch = new JSch();
|
|
|
+ Session session = null;
|
|
|
+ ChannelSftp sftpChannel = null;
|
|
|
+ FileInputStream inputStream = null;
|
|
|
+ try {
|
|
|
+ session = jsch.getSession(user, server, port);
|
|
|
+ session.setPassword(password);
|
|
|
+ session.setConfig("StrictHostKeyChecking", "no");
|
|
|
+ session.connect();
|
|
|
+
|
|
|
+ sftpChannel = (ChannelSftp) session.openChannel("sftp");
|
|
|
+ sftpChannel.connect();
|
|
|
+
|
|
|
+ String remoteFilePath = (remoteDir.endsWith("/")?remoteDir: (remoteDir + "/")) + file.getName();
|
|
|
+ inputStream = new FileInputStream(file);
|
|
|
+
|
|
|
+ sftpChannel.put(inputStream, remoteFilePath);
|
|
|
+ } finally {
|
|
|
+ if (inputStream != null) {
|
|
|
+ inputStream.close();
|
|
|
+ }
|
|
|
+ if (sftpChannel != null) {
|
|
|
+ sftpChannel.disconnect();
|
|
|
+ }
|
|
|
+ if (session != null) {
|
|
|
+ session.disconnect();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|