步骤:
1、在远程服务器上搭建sftp服务
第一步:在服务器上(windows server 2012 R2)下载 freessh。
链接: http://www.freesshd.com/?ctt=download.
(下载freeSSHd.exe)
第二步:配置freesshd
链接: https://www.jianshu.com/p/438b2b4dc6e8.
第三步:验证sftp服务是否搭建成功??
可通过WinSCP查验。
WinSCP是一个Windows环境下使用SSH的开源图形化SFTP客户端。
2、Java实现sftp上传文件
依赖的jar包
<!-- sftp -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
config文件
#sftp
sftp.host=1.1.1.1
sftp.port=22
sftp.userName=sftp
sftp.password=sftp
Sftp实体类
@Setter
@Getter
public class Sftp {
private String innerhost;
private int innerport;
private String inneruserName;
private String innerpassword;
public Sftp(String innerhost, int innerport, String inneruserName, String innerpassword) {
// TODO Auto-generated constructor stub
this.innerhost = innerhost;
this.innerport = innerport;
this.inneruserName = inneruserName;
this.innerpassword = innerpassword;
}
}
配置Config
@Configuration
public class SftpConfig {
@Bean
public Sftp getSftp() throws IOException{
String filePath = System.getProperty("user.dir") + "/config/config.properties";
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
Properties properties = new Properties();
properties.load(in);
String host = properties.getProperty("sftp.host");
int port = Integer.valueOf(properties.getProperty("sftp.port")).intValue();
String userName = properties.getProperty("sftp.userName");
String password = properties.getProperty("sftp.password");
return new Sftp(host, port, userName, password);
}
}
sftp工具类
public class SftpUtil {
private static ChannelSftp sftp = null;
private static Session sshSession = null;
private static Integer i = 0;
/**
* 通过SFTP连接服务器
*/
public static ChannelSftp connect(String ip, String username, String password, Integer port) throws Exception {
JSch jsch = new JSch();
try {
if (port <= 0) {
// 连接服务器,采用默认端口
sshSession = jsch.getSession(username, ip);
} else {
// 采用指定的端口连接服务器
sshSession = jsch.getSession(username, ip, port);
}
// 如果服务器连接不上,则抛出异常
if (sshSession == null) {
throw new Exception("服务器异常");
}
// 设置登陆主机的密码
sshSession.setPassword(password);// 设置密码
// 设置第一次登陆的时候提示,可选值:(ask | yes | no)
sshSession.setConfig("StrictHostKeyChecking", "no");
// 设置登陆超时时间
sshSession.connect(300000);
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return sftp;
}
/**
* 关闭连接
*/
public static void disconnect() {
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
if (sshSession != null) {
if (sshSession.isConnected()) {
sshSession.disconnect();
}
}
}
/**
* 上传单个文件
*
* @param remotePath:远程保存目录
* @param localPath:本地上传目录(以路径符号结束)
* @return
*/
public static void uploadFile(String remotePath, String localPath) throws Exception {
FileInputStream in = null;
File localFile = new File(localPath);
sftp.cd(remotePath);
in = new FileInputStream(localFile);
sftp.put(in, localFile.getName());
if (in != null) {
in.close();
}
}
/**
* 批量上传文件
*
* @param remotePath:远程保存目录
* @param localPath:本地上传目录
* @return
*/
public static boolean bacthUploadFile(String remotePath, String localPath) throws Exception {
boolean flag = true;
// 进入远程路径
try {
if (!isDirExist(remotePath)) {
// 目录不存在,则创建文件夹
String[] dirs = remotePath.split("/");
String tempPath = "";
for (String dir : dirs) {
if (null == dir || "".equals(dir))
continue;
tempPath += "/" + dir;
try {
sftp.cd(tempPath);
} catch (SftpException ex) {
sftp.mkdir(tempPath);
sftp.cd(tempPath);
}
}
sftp.cd(remotePath);
} else {
sftp.cd(remotePath);
}
// 本地文件上传
File file = new File(localPath);
// 本地文件上传方法
copyFile(file, sftp.pwd());
} catch (Exception e) {
e.printStackTrace();
flag = false;
throw e;
}
return flag;
}
private static void copyFile(File file, String pwd) throws Exception {
//不是目录,直接进入改变后的远程路径,进行上传
sftp.cd(pwd);
System.out.println("正在复制文件:" + file.getAbsolutePath());
InputStream instream = null;
OutputStream outstream = null;
outstream = sftp.put(file.getName());
instream = new FileInputStream(file);
byte b[] = new byte[1024];
int n;
while ((n = instream.read(b)) != -1) {
outstream.write(b, 0, n);
}
outstream.flush();
outstream.close();
instream.close();
}
/**
* 删除本地文件
*
* @param filePath
* @return
*/
public boolean deleteFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return false;
}
if (!file.isFile()) {
return false;
}
boolean rs = file.delete();
return rs;
}
/**
* 创建目录
*
* @param createpath
* @return
*/
public static void createDir(String createpath) {
try {
if (isDirExist(createpath)) {
sftp.cd(createpath);
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
// 建立目录
sftp.mkdir(filePath.toString());
// 进入并设置为当前目录
sftp.cd(filePath.toString());
}
}
} catch (SftpException e) {
e.printStackTrace();
}
}
/**
* 判断目录是否存在
*
* @param directory
* @return
*/
public static boolean isDirExist(String directory) {
try {
Vector<?> vector = sftp.ls(directory);
if (null == vector) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
/**
* 删除stfp文件
*
* @param directory:要删除文件所在目录
*/
public static void deleteSFTP(String directory) {
try {
if (isDirExist(directory)) {
Vector<ChannelSftp.LsEntry> vector = sftp.ls(directory);
if (vector.size() == 1) { // 文件,直接删除
sftp.rm(directory);
} else if (vector.size() == 2) { // 空文件夹,直接删除
sftp.rmdir(directory);
} else {
String fileName = "";
// 删除文件夹下所有文件
for (ChannelSftp.LsEntry en : vector) {
fileName = en.getFilename();
if (".".equals(fileName) || "..".equals(fileName)) {
continue;
} else {
deleteSFTP(directory + "/" + fileName);
}
}
// 删除文件夹
sftp.rmdir(directory);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 如果目录不存在就创建目录
*
* @param path
*/
public void mkdirs(String path) {
File f = new File(path);
String fs = f.getParent();
f = new File(fs);
if (!f.exists()) {
f.mkdirs();
}
}
}
Controller
@Autowired
private SftpConfig readSftpConfig;
@PostMapping("/sftptest")
public void test1(String[] args) throws IOException {
ChannelSftp channelSftp = null;
String localPath = "D:\\Daisy\\SftpTest\\test.jpg";
String remotePath = "/SftpTest";(此目录为远程保存目录,可没有该文件夹,会自行创建)
try {
Sftp sftp = readSftpConfig.getSftp();
channelSftp = SftpUtil.connect(sftp.getInnerhost(), sftp.getInneruserName(), sftp.getInnerpassword(), sftp.getInnerport());
// 上传
SftpUtil.bacthUploadFile(remotePath, localPath);
} catch (Exception e) {
e.printStackTrace();
} finally {
channelSftp.disconnect();
}
}
测试结果
图片1为本地图片
图片2为经过测试,上传至服务器的图片。