Java如何实现上传文件到服务器指定目录
作者:yaominghui 发布时间:2021-10-16 14:38:31
前言需求
使用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
@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容器。
来源:https://www.cnblogs.com/jichi/p/12158537.html


猜你喜欢
- 本文实例讲述了java实现一次性压缩多个文件到zip中的方法。分享给大家供大家参考,具体如下:1.需要引入包:import java.io.
- 本文实例为大家分享了Android实现APP秒表功能的具体代码,供大家参考,具体内容如下这几天一直在看安卓,也正好赶上老师布置的作业,所以就
- 本文实例为大家分享了java导出百万以上数据的excel文件,供大家参考,具体内容如下1.传统的导出方式会消耗大量的内存,2003每个she
- 今日遇到一个问题:springboot需要获取到一个自定义名称文件夹下的静态资源(图片等),并且文件夹的路径不在classPath下面,而是
- 崩溃来源使用过AIDL进行跨进程通信的同学,肯定遇到过DeadObjectException这个崩溃,那么这个崩溃是怎么来的,我们又该如何解
- 一、前言前面我们讲了Java的入门知识,相信许多小伙伴对Java基础有一个大概的认识了,这也为我们后续的学习打下了基础,所以我们可以继续学习
- 我就废话不多说了,大家还是直接看代码吧~<select id="getBiTree" parameterType=
- 最近项目上用就hibernate+spring data jpa,一开始感觉还不错,但是随着对业务的复杂,要求处理一些复杂的sql,就顺便研
- c#控件实现类似c++中ocx控件功能c++中ocx控件1、控件方法2、控件事件c#很容易实现c++中ocx中控件方法的功能,但是实现类似c
- graylog配置springboot配置依赖compile group: 'de.siegmar', name: '
- Mybatis 有两种实现方式其一:通过xml配置文件实现其二:面向接口编程的实现  
- 大多数的B2C商城项目都会有限时活动,当用户下单后都会有支付超时时间,当订单超时后订单的状态就会自动变成已取消 ,这个功能的实现
- 最近项目中遇到一个问题,在用户没填数据的时候,我们需要接收从前端传过来的对象为null,但是前端说他们一个一个判断特别麻烦,只能传个空对象过
- SpringBoot中的过滤器 * 操作与springmvc中的几乎一样所以这里也不过多介绍了,下面举两
- Java 中的引用类型:强引用、软引用、弱引用和虚引用强引用如 Object object = new Object(),那 object
- 上次老师跟大家分享了 cookie、session和token,今天给大家分享一下Java 8中的Stream API。Stream简介1、
- JWT可以理解为一个加密的字符串,里面由三部分组成:头部(Header)、负载(Payload)、签名(signature)由base64加
- 如何将ResultSet结果集遍历到List中今天在使用jstl标签展示查询结果时遇到一个小问题,即如何将ResultSet对象传递给前台页
- 前言最近在开发项目的时候涉及到复杂的动态条件查询,但是mybaits本身不支持if elseif类似的判断但是我们可以间接通过 chose
- kotlin基础教程之类和继承类声明使用class关键字声明类,查看其声明格式:: modifiers ("class"