本来打算用ftp或者sftp上传,但是都失败了,直到发现了JSch
服务器使用的是阿里云,免费一个月,默认开启了22端口
public static void main(String[] args) {
String username = "root";
String password = "********";
String host = "********";
int port = 22;
// 创建JSch对象
JSch jSch = new JSch();
Session jSchSession = null;
ChannelSftp chSftp = null;
try {
// 根据主机账号、ip、端口获取一个Session对象
jSchSession = jSch.getSession(username, host, port);
// 存放主机密码
jSchSession.setPassword(password);
// 去掉首次连接确认
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
jSchSession.setConfig(config);
// 超时连接时间为3秒
jSchSession.setTimeout(3000);
// 进行连接
jSchSession.connect();
// 打开SFTP通道
chSftp = (ChannelSftp)jSchSession.openChannel("sftp");
// 建立SFTP通道的连接
chSftp.connect();
// 设置编码格式
chSftp.setFilenameEncoding("UTF-8");
/**
* 说明:
* 1、当前文件上传信息没有任何反馈,如果没有异常则代表成功
* 2、如果需要判断是否读取成功的进度,可参考https://blog.csdn.net/coding99/article/details/52416373?locationNum=13&fps=1
* 3、将文件上传到服务器中nginx的根目录下
*/
chSftp.put("E:\\download\\b7dae00ace525b8a12fb3d6b4bdac007.jpeg", "/usr/local/nginx/html/images");
log.info("文件上传成功");
} catch (JSchException | SftpException e) {
log.warn(e.getMessage());
} finally {
// 关闭sftpChannel
if (chSftp != null && chSftp.isConnected()) {
chSftp.quit();
}
// 关闭jschSesson流
if (jSchSession != null && jSchSession.isConnected()) {
jSchSession.disconnect();
}
}
}