前言需求

使用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. Mybatis/Ibatis,数据库操作的返回值

    该问题,我百度了下,根本没发现什么有价值的文章:还是看源代码(详见最后附录)中的注释,最有效了!insert,返回值是:新插入行的主键(primary key):需要包含<selectKey&g ...

  2. php 第三方登录总结OAuth协议

  3. Bootstrap之Form表单验证神器: BootstrapValidator(转)

    前言:做Web开发的我们,表单验证是再常见不过的需求了.友好的错误提示能增加用户体验.博主搜索bootstrap表单验证,搜到的结果大部分都是文中的主题:bootstrapvalidator.今天就来 ...

  4. iptables禁止icmp端口

    除192.168.62.1外,禁止其它人ping我的主机 #iptables -A INPUT -i eth0 -s 192.168.62.1/32 -p icmp -m icmp --icmp-ty ...

  5. HDU1358 Period 题解 KMP算法

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1358 题目大意:给你一个长度为 \(n\) 的字符串 \(s\) ,那么它有 \(n\) 个前缀. 对 ...

  6. img的alt和title的异同?

    alt 是图片加载失败时,显示在网页上的替代文字: title 是鼠标放上面时显示的文字,title是对图片的描述与进一步说明; 这些都是表面上的区别,alt是img必要的属性,而title不是. 对 ...

  7. 深入Java线程管理(一):线程的实现方式

    Java的线程实现方式一共有三种,继承Thread.实现Runable接口,实现Callable接口.不过实现Runnable接口与实现Callable接口的方式基本相同,只是Callable接口里定 ...

  8. Spring与C3p0连接数据库对事务操作

    maven包: <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncodin ...

  9. Spring Cloud探路(三)REST 客户端Feign

    Declarative REST Client: Feign Feign is a declarative web service client. It makes writing web servi ...

  10. dotnet core 使用 CoreRT 将程序编译为 Native 程序

    现在微软有一个开源项目 CoreRT 能通过将托管的 .NET Core 编译为单个无依赖的 Native 程序 这个项目现在还没发布,但是能尝试使用,可以带来很多的性能提升 使用 CoreRT 发布 ...