首先添加依赖
<!--sftp文件上传-->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
代码
/**
* 利用JSch包实现SFTP上传文件
* @param bytes 文件字节流
* @param fileName 文件名
* @throws Exception
*/
public static void sshSftp(byte[] bytes,String fileName) throws Exception{
int port = 22;
String user = "用户名";
String password = "密码";
String ip = "公网IP";
// 服务器保存路径
String filepath = "/home/image";
Session session = null;
Channel channel = null;
JSch jSch = new JSch();
if(port <=0){
//连接服务器,采用默认端口
session = jSch.getSession(user, ip);
}else{
//采用指定的端口连接服务器
session = jSch.getSession(user, ip ,port);
}
//如果服务器连接不上,则抛出异常
if (session == null) {
throw new Exception("session is null");
}
//设置登陆主机的密码
session.setPassword(password);//设置密码
//设置第一次登陆的时候提示,可选值:(ask | yes | no)
session.setConfig("userauth.gssapi-with-mic","no");
session.setConfig("StrictHostKeyChecking", "no");
//设置登陆超时时间
session.connect(30000);
OutputStream outstream = null;
try {
//创建sftp通信通道
channel = (Channel) session.openChannel("sftp");
channel.connect(1000);
ChannelSftp sftp = (ChannelSftp) channel;
//进入服务器指定的文件夹
sftp.cd(filepath);
//以下代码实现从本地上传一个文件到服务器,如果要实现下载,对换一下流就可以了
outstream = sftp.put(fileName);
outstream.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
//关流操作
if (outstream != null) {
outstream.flush();
outstream.close();
}
if (session != null) {
session.disconnect();
}
if (channel != null) {
channel.disconnect();
}
System.out.println("上传成功!");
}
}
//将图片转字节流
public static byte[] image2Bytes(String imgSrc) throws Exception {
FileInputStream file = new FileInputStream(new File(imgSrc));
//可能溢出,简单起见就不考虑太多,如果太大就要另外想办法,比如一次传入固定长度byte[]
byte[] bytes = new byte[file.available()];
//将文件内容写入字节数组,提供测试的case
file.read(bytes);
file.close();
return bytes;
}
public static void main(String[] args) {
try {
String srcUrl = "F://Projects//Python//bs//images//1833.jpeg";//本地路径
File file = new File(srcUrl.trim());
String fileName = file.getName();
byte[] b =image2Bytes(srcUrl);
sshSftp(b,fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
上传完成后通过配置Nginx就可以将图片直接在公网被访问了,如果上传失败记得检查端口、用户名、密码这些有没有错误
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/279435.html