java将文件发送到远程文件服务器并将niginx路径返回
public static String saveToMoveTool(MultipartFile multipartFile) throws Exception {
//创建一个文件路径在项目本地路径
File file = new File("/static/img/");
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
//打开服务器会话
Session s = getSession("10.10.10.10", 22, "root", "password");
//文件保存的服务器位置
String filePath = "/opt/project/imgs/";
//自己的nginx路径,用于返回文件url
String nginxPath = "http://10.10.10.10:1234/";
//获取会话通道
Channel channel = getChannel(s);
//转换通道类型
ChannelSftp sftp = (ChannelSftp) channel;
//上传文件到指定目录
String upload = uploadFile(sftp, filePath, file);
//关闭通道
closeAll(sftp, channel, s);
return nginxPath + upload;
}
getSession()
public static Session getSession(String host, int port, String username, final String password) {
Session session = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties sshConfig = new Properties();
//关闭严格密钥检查
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.connect();
LOG.info("连接成功!");
} catch (JSchException e) {
LOG.info("连接失败!", e);
}
return session;
}
getChannel()
public static Channel getChannel(Session session) {
Channel channel = null;
try {
channel = session.openChannel("sftp");
channel.connect();
LOG.info("获取通道成功!");
} catch (JSchException e) {
LOG.info("获取通道失败!", e);
}
return channel;
}
uploadFile()
public static String uploadFile(ChannelSftp sftp, String dir, File file) {
String result = "";
try {
sftp.cd(dir);;
if (file != null) {
//NetImgSaveUtil.generateShortUuid()是获取一个八位UUID的方法,可替换成自己的
String name = NetImgSaveUtil.generateShortUuid();
sftp.put(new FileInputStream(file), name);
result = name;
} else {
result = "文件为空!不能上传!";
}
} catch (Exception e) {
LOG.info("上传失败!", e);
result = "上传失败!";
}
return result;
}
closeAll()
public static void closeAll(ChannelSftp sftp, Channel channel, Session session) {
try {
closeChannel(sftp);
closeChannel(channel);
closeSession(session);
} catch (Exception e) {
LOG.info("所有流已关闭!", e);
}
}
*Nginx代理
server {
listen 2350;
server_name 10.101.6.3 ;
location ~ .*\.(png|jpg)$ {
expires 24h;
root /opt/project/imgs;#指定图片存放路径
}
}
./sbin/nginx -s reload 刷新配置