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;@Asyncpublic 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实现上传文件到指定服务器指定目录相关推荐
- vba上传文件到ftp服务器指定目录下面
vba上传文件到ftp服务器指定目录 +脚本形式 文章目录 1. 测试版本无校验: 2. 测试版本有检验 3. 文件不存在校验版本 4. 文件不存在校验+必填项校验版本 1. 测试版本无校验: Sub ...
- java怎么上传文件到web服务器_Java客户端通过Http发送POST请求上传文件到web服务器...
http://www.cnblogs.com/WilliamJiang/archive/2012/04/29/2475883.html 1.朋友的一个需求,让我给他实现,需求是这样的,需要用ASP.n ...
- java 实现上传文件到远程服务器
阿里云低价服务器1折特惠,优惠爽翻天,点我立即低价购买 import java.io.DataOutputStream; import java.io.File; import java.io.Fil ...
- linux上传文件至指定目录下,node上传文件到linux服务器指定路径
'use strict' const Client = require('ssh2-sftp-client') const config = { path: { // 远程地址 romotePath: ...
- java ftp 上传文件到服务器,java实现ftp上传文件到服务器
java实现ftp上传文件到服务器 内容精选 换一换 怎样上传文件到Windows操作系统云服务器?安装传输工具在本地主机和Windows云服务器上分别安装数据传输工具,将文件上传到云服务器.例如QQ ...
- Java服务器与客户端传文件,java实现上传文件到服务器和客户端.pdf
java实实现现上上传传文文件件到到服服务务器器和和客客户户端端 这篇文章主要为大家详细介绍了java实现上传文件到服务器和客户端,具有一定的参考价值,感兴趣的小伙伴们 以参考一下 JAVA编写一个 ...
- 怎么样向云服务器上传文件_向云服务器上传文件以及移动到指定文件夹
向云服务器上传文件以及移动到指定文件夹 一.上传文件到云服务器 1. 打开 CuteFTP ,服务器 IP 地址设置为 101.227.245.9 .用户名和密码为空,端口 21 ,点击连接: 出现对 ...
- JAVA上传文件图片到服务器保存
这里我记录一个比较简单方便操作的JAVA上传文件图片到服务器并且保存! 首先是页面 html的 我这是提交一个文件和类型 <div style="border: 1px solid ...
- java上传文件到FTP服务器
欢迎来到小生的博客,各种工具类,常用知识点.技巧持续更新中....... 感谢大家点赞关注,希望大家能够给小生更多的支持. 祝您阅读愉快! 有任何疑问可以加小生QQ群咨询:107680366 前段时间 ...
- java上传文件到远程服务器(一)---HttpURLConnection方式
我们在之前的文章 JavaWeb静态资源分离思路 中已经了解到要把文件上传到静态资源服务器有三种方式: java上传文件到ftp服务器(这个方案需要在静态资源服务器安装ftp服务) java使用Htt ...
最新文章
- 那些有趣的Webview细节
- Python进程、线程、协程详解
- python代码格式-设置Python代码格式
- 大数据陷阱:谁有权享有大数据,谁有权分析大数据
- 数据中心架构有哪些组件?
- java中outer的使用
- Struts2 datetimepicker 日期月份乱码解决
- jz2440-uboot-201204版本移植【学习笔记】【原创】
- x轴z轴代表的方向图片_游戏中到底是Z轴朝上还是Y轴朝上?
- cdatabase读取excel第一行数据_pandas读取excel数据并对重复数据进行标记或者删除
- Oracle --JOB
- 查询mysql 中的空文本_MySQL查询以显示空列的自定义文本
- 你自己的事,你不操心谁操心?
- MITRE 发布防御知识库 Shield
- 3G手机J2ME开发环境搭建(eclipse3开发j2me环境搭建)
- 到底要不要去外包公司?这篇带你全面了解外包那些坑!
- android播放器(music player)源码分析4(StreamStarter,URLEncoder)
- 搭建一款属于自己的,微信/抖音小程序,通过广告赚钱
- 如何通过Android日历api插入日程(事件)和提醒(通知)
- 多线程程序的填坑笔记和多线程编程应该遵循的规则