Java实现上传文件到指定服务器指定目录
前言需求
使用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实现上传文件到指定服务器指定目录的更多相关文章
- java 上传文件到 ftp 服务器
1. java 上传文件到 ftp 服务器 package com.taotao.common.utils; import java.io.File; import java.io.FileInpu ...
- SpringBoot 上传文件到linux服务器 异常java.io.FileNotFoundException: /tmp/tomcat.50898……解决方案
SpringBoot 上传文件到linux服务器报错java.io.FileNotFoundException: /tmp/tomcat.50898-- 报错原因: 解决方法 java.io.IOEx ...
- app端上传文件至服务器后台,web端上传文件存储到服务器
1.android前端发送服务器请求 在spring-mvc.xml 将过滤屏蔽(如果不屏蔽 ,文件流为空) <!-- <bean id="multipartResolver&q ...
- Java ftp上传文件方法效率对比
Java ftp上传文件方法效率对比 一.功能简介: txt文件采用ftp方式从windows传输到Linux系统: 二.ftp实现方法 (1)方法一:采用二进制流传输,设置缓冲区,速度快,50M的t ...
- SpringBoot上传文件到本服务器 目录与jar包同级问题
目录 前言 原因 实现 不要忘记 最后的封装 Follow up 前言 看标题好像很简单的样子,但是针对使用jar包发布SpringBoot项目就不一样了.当你使用tomcat发布项目的时候,上传 ...
- asp.net 服务器 上传文件到 FTP服务器
private string ftpServerIP = "服务器ip";//服务器ip private string ftpUserID = "ftp的用户名" ...
- C# 上传文件至远程服务器
C# 上传文件至远程服务器(适用于桌面程序及web程序) 2009-12-30 19:21:28| 分类: C#|举报|字号 订阅 最近几天在玩桌面程序,在这里跟大家共享下如何将本地文件上传 ...
- ASP.NET上传文件到远程服务器(HttpWebRequest)
/// <summary> /// 文件上传至远程服务器 /// </summary> /// <param name="url">远程服务地址 ...
- .Net 上传文件到ftp服务器和下载文件
突然发现又很久没有写博客了,想起哎呦,还是写一篇博客记录一下吧,虽然自己还是那个渣渣猿. 最近在做上传文件的功能,上传到ftp文件服务器有利于管理上传文件. 前面的博客有写到layui如何上传文件,然 ...
- PHP 上传文件到其他服务器
PHP 上传文件到其他服务器 标签(空格分隔): 安装Guzzle类库 **guzzle** 是发送网络请求的类库 composer安装:**composer require guzzlehttp/g ...
随机推荐
- day3_python之函数参数
一.形参 在定义函数时,括号内的参数称为形参,特点:形参就是变量名 def foo(x, y): # x=1,y=2 print(x) print(y) 二.实参 在调用函数时,括号内的参数成为实参, ...
- tensorflow入门——5tensorflow安装
你将把你学到的神经网络的知识,借助 TensorFlow ,一个 Google 开源的深度学习框架,应用在真实的数据集中. 你将使用 TensorFlow 来辨别 notMNIST 数据集.它是一个由 ...
- SVG和canvas画图,js求数组最大最小值
windows命令行的内容怎么复制,右键选择标记,选中内容后再点击鼠标右键就复制了. 安装Node.js后再用npm install命令会出现如下warn:saveError ENOENT: no s ...
- 2018-2-13-win10-uwp-ContentDialog-点确定不关闭
title author date CreateTime categories win10 uwp ContentDialog 点确定不关闭 lindexi 2018-2-13 17:23:3 +08 ...
- Math.abs( x )
Math.abs( x ) 下面是参数的详细信息: x : 一个数字 返回值: 返回一个数字的绝对值 <html> <head> <title>JavaScript ...
- centos7搭建集群必知:centos7已经无iptables,只有firewall
1.防火墙概述 centos7搭建集群,发现没有iptables,需要安装.防火墙为firewalle CentOS7默认的防火墙不是iptables,而是firewalle. CentOS 7.0默 ...
- Codeforces Round #196 (Div. 1 + Div. 2)
A. Puzzles 对\(f[]\)排序,取连续的\(m\)个. B. Routine Problem 考虑\(\frac{a}{b}\)和\(\frac{c}{d}\)的大小关系,适配后就是分数的 ...
- Linux创建用户、设置密码、修改用户、删除用户命令
与大家分享下Linux系统中创建用户.设置密码.修改用户.删除用户的命令,希望对你有所帮助. useradd testuser 创建用户testuserpasswd testuser 给已创建的用 ...
- vue通信、传值的方式
原文博主地址:https://blog.csdn.net/qq_35430000/article/details/79291287 看完还是受益匪浅,讲得很详细..感谢!
- win10 uwp 使用 Microsoft.Graph 发送邮件
在 2018 年 10 月 13 号参加了 张队长 的 Office 365 训练营 学习如何开发 Office 365 插件和 OAuth 2.0 开发,于是我就使用 UWP 尝试使用 Micros ...