前言需求

使用freemarker生成的静态文件,统一存储在某个服务器上。本来一开始打算使用ftp实现的,奈何老连接不上,改用jsch。毕竟有现成的就很舒服,在此介绍给大家。

具体实现

引入的pom

<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency> <dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>

建立实体类

public class ResultEntity {

    private String code;

    private String message;

    private File file;

    public ResultEntity(){}

	public ResultEntity(String code, String message, File file) {
super();
this.code = code;
this.message = message;
this.file = file;
} public String getCode() {
return code;
} public void setCode(String code) {
this.code = code;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public File getFile() {
return file;
} public void setFile(File file) {
this.file = file;
} }
public class ScpConnectEntity {
private String userName;
private String passWord;
private String url;
private String targetPath; public String getTargetPath() {
return targetPath;
} public void setTargetPath(String targetPath) {
this.targetPath = targetPath;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPassWord() {
return passWord;
} public void setPassWord(String passWord) {
this.passWord = passWord;
} public String getUrl() {
return url;
} public void setUrl(String url) {
this.url = url;
} }

建立文件上传工具类

@Configuration
public class FileUploadUtil { @Value("${remoteServer.url}")
private String url; @Value("${remoteServer.password}")
private String passWord; @Value("${remoteServer.username}")
private String userName; @Async
public ResultEntity uploadFile(File file, String targetPath, String remoteFileName) throws Exception{
ScpConnectEntity scpConnectEntity=new ScpConnectEntity();
scpConnectEntity.setTargetPath(targetPath);
scpConnectEntity.setUrl(url);
scpConnectEntity.setPassWord(passWord);
scpConnectEntity.setUserName(userName); String code = null;
String message = null;
try {
if (file == null || !file.exists()) {
throw new IllegalArgumentException("请确保上传文件不为空且存在!");
}
if(remoteFileName==null || "".equals(remoteFileName.trim())){
throw new IllegalArgumentException("远程服务器新建文件名不能为空!");
}
remoteUploadFile(scpConnectEntity, file, remoteFileName);
code = "ok";
message = remoteFileName;
} catch (IllegalArgumentException e) {
code = "Exception";
message = e.getMessage();
} catch (JSchException e) {
code = "Exception";
message = e.getMessage();
} catch (IOException e) {
code = "Exception";
message = e.getMessage();
} catch (Exception e) {
throw e;
} catch (Error e) {
code = "Error";
message = e.getMessage();
}
return new ResultEntity(code, message, null);
} private void remoteUploadFile(ScpConnectEntity scpConnectEntity, File file,
String remoteFileName) throws JSchException, IOException { Connection connection = null;
ch.ethz.ssh2.Session session = null;
SCPOutputStream scpo = null;
FileInputStream fis = null; try {
createDir(scpConnectEntity);
}catch (JSchException e) {
throw e;
} try {
connection = new Connection(scpConnectEntity.getUrl());
connection.connect(); if(!connection.authenticateWithPassword(scpConnectEntity.getUserName(),scpConnectEntity.getPassWord())){
throw new RuntimeException("SSH连接服务器失败");
}
session = connection.openSession(); SCPClient scpClient = connection.createSCPClient(); scpo = scpClient.put(remoteFileName, file.length(), scpConnectEntity.getTargetPath(), "0666");
fis = new FileInputStream(file); byte[] buf = new byte[1024];
int hasMore = fis.read(buf); while(hasMore != -1){
scpo.write(buf);
hasMore = fis.read(buf);
}
} catch (IOException e) {
throw new IOException("SSH上传文件至服务器出错"+e.getMessage());
}finally {
if(null != fis){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != scpo){
try {
scpo.flush();
// scpo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != session){
session.close();
}
if(null != connection){
connection.close();
}
}
} private boolean createDir(ScpConnectEntity scpConnectEntity ) throws JSchException { JSch jsch = new JSch();
com.jcraft.jsch.Session sshSession = null;
Channel channel= null;
try {
sshSession = jsch.getSession(scpConnectEntity.getUserName(), scpConnectEntity.getUrl(), 22);
sshSession.setPassword(scpConnectEntity.getPassWord());
sshSession.setConfig("StrictHostKeyChecking", "no");
sshSession.connect();
channel = sshSession.openChannel("sftp");
channel.connect();
} catch (JSchException e) {
e.printStackTrace();
throw new JSchException("SFTP连接服务器失败"+e.getMessage());
}
ChannelSftp channelSftp=(ChannelSftp) channel;
if (isDirExist(scpConnectEntity.getTargetPath(),channelSftp)) {
channel.disconnect();
channelSftp.disconnect();
sshSession.disconnect();
return true;
}else {
String pathArry[] = scpConnectEntity.getTargetPath().split("/");
StringBuffer filePath=new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
try {
if (isDirExist(filePath.toString(),channelSftp)) {
channelSftp.cd(filePath.toString());
} else {
// 建立目录
channelSftp.mkdir(filePath.toString());
// 进入并设置为当前目录
channelSftp.cd(filePath.toString());
}
} catch (SftpException e) {
e.printStackTrace();
throw new JSchException("SFTP无法正常操作服务器"+e.getMessage());
}
}
}
channel.disconnect();
channelSftp.disconnect();
sshSession.disconnect();
return true;
} private boolean isDirExist(String directory,ChannelSftp channelSftp) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = channelSftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
}

属性我都写在Spring的配置文件里面了。将这个类托管给spring容器。

如果在普通类里面使用这个类,就需要看一下上篇博客了。哈哈。

总结

在我们使用的时候,主要调uploadFile这个方法即可。传递File文件,目标路径及文件名称。

Java实现上传文件到指定服务器指定目录的更多相关文章

  1. java 上传文件到 ftp 服务器

    1.  java 上传文件到 ftp 服务器 package com.taotao.common.utils; import java.io.File; import java.io.FileInpu ...

  2. SpringBoot 上传文件到linux服务器 异常java.io.FileNotFoundException: /tmp/tomcat.50898……解决方案

    SpringBoot 上传文件到linux服务器报错java.io.FileNotFoundException: /tmp/tomcat.50898-- 报错原因: 解决方法 java.io.IOEx ...

  3. app端上传文件至服务器后台,web端上传文件存储到服务器

    1.android前端发送服务器请求 在spring-mvc.xml 将过滤屏蔽(如果不屏蔽 ,文件流为空) <!-- <bean id="multipartResolver&q ...

  4. Java ftp上传文件方法效率对比

    Java ftp上传文件方法效率对比 一.功能简介: txt文件采用ftp方式从windows传输到Linux系统: 二.ftp实现方法 (1)方法一:采用二进制流传输,设置缓冲区,速度快,50M的t ...

  5. SpringBoot上传文件到本服务器 目录与jar包同级问题

    目录 前言 原因 实现 不要忘记 最后的封装 Follow up   前言 看标题好像很简单的样子,但是针对使用jar包发布SpringBoot项目就不一样了.当你使用tomcat发布项目的时候,上传 ...

  6. asp.net 服务器 上传文件到 FTP服务器

    private string ftpServerIP = "服务器ip";//服务器ip private string ftpUserID = "ftp的用户名" ...

  7. C# 上传文件至远程服务器

    C# 上传文件至远程服务器(适用于桌面程序及web程序) 2009-12-30 19:21:28|  分类: C#|举报|字号 订阅     最近几天在玩桌面程序,在这里跟大家共享下如何将本地文件上传 ...

  8. ASP.NET上传文件到远程服务器(HttpWebRequest)

    /// <summary> /// 文件上传至远程服务器 /// </summary> /// <param name="url">远程服务地址 ...

  9. .Net 上传文件到ftp服务器和下载文件

    突然发现又很久没有写博客了,想起哎呦,还是写一篇博客记录一下吧,虽然自己还是那个渣渣猿. 最近在做上传文件的功能,上传到ftp文件服务器有利于管理上传文件. 前面的博客有写到layui如何上传文件,然 ...

  10. PHP 上传文件到其他服务器

    PHP 上传文件到其他服务器 标签(空格分隔): 安装Guzzle类库 **guzzle** 是发送网络请求的类库 composer安装:**composer require guzzlehttp/g ...

随机推荐

  1. Python基础10 回顾

    从最初的"Hello World",走到面向对象,该回过头来看看,教程中是否遗漏了什么. 我们之前提到一句话,"Everything is Object".那么 ...

  2. react项目安装及运行

    博客地址 :https://www.cnblogs.com/sandraryan/ 安装node ,有就跳过. node.js官网:https://nodejs.org/en/ 终端用node -v ...

  3. BERT大火却不懂Transformer?读这一篇就够了 原版 可视化机器学习 可视化神经网络 可视化深度学习

    https://jalammar.github.io/illustrated-transformer/ The Illustrated Transformer Discussions: Hacker ...

  4. hdu 1289 Hat’s IEEE

    Problem - 1289 好题.其实就是模拟IEEE754的格式,不过要注意的是,这里用的32位是float,用double就不对了. 代码如下: #include <cstdio> ...

  5. html--图片img

    一.图片的基本格式 当前万维网上流行的图像格式以GIF及JPEG为主,另外还有一个PNG.以下做分别介绍: 1.GIF格式:采用LZW压缩,是以压缩相同颜色的色块来减少图像大小的.(LZW压缩是一种能 ...

  6. js实现圆形的碰撞检测

    文章地址:https://www.cnblogs.com/sandraryan/ 碰撞检测这个东西写小游戏挺有用der~~~ 注释写的还挺全,所以就不多说了,看注释 这是页面结构.wrap存放生成的小 ...

  7. Python--day62--ORM的使用

    4.Django里ORM的使用 1,手动创建数据库 2,在settings.py里面,配置数据库的连接信息 3,在项目/__init__.py告诉Django用pymysql模块代替MySQLdb(不 ...

  8. gyp verb check python checking for Python executable "python2" in the PATH

    缺少python2.7支持 可快速使用以下语句完成安装 npm install --global --production windows-build-tools 到时候会自动下载python的 如果 ...

  9. C# 标准性能测试

    经常我写一个类,作为一个工具类,小伙伴会问我这个类的性能,这时我就需要一个标准的工具进行测试. 本文告诉大家如何使用 benchmarkdotnet 做测试. 现在在 github 提交代码,如果有小 ...

  10. P1087 N个数的最大公约数

    题目描述 今天灵灵学习了使用欧几里得算法(即:辗转相除法)求解两个数的最大公约数.于是他决定用这个方法求解 \(N\) 个数的最大公约数. 输入格式 输入的第一行包含一个整数 \(N(1 \le N ...