公司系统中上传功能不合理场景:windows本地和linux远程写入的文件都在本地,导致本地和远程不能访问同一资源。
一番思考,找到一种方案:不管哪种环境,都统一写到linux远程服务器。就能实现资源在不同环境下的共享。
实现过程:
1.引入jar包
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
2.连接服务器写流
JSch jsch = new JSch();//用于建立连接
Session session = null;
try {
//配置表中查出linux服务器登录信息
Map<String,Object> map =iCommonConfigurationService.getLoginLinux();
//用户名、ip地址、端口号
session = jsch.getSession((String)map.get(“user”), (String)map.get(“ip”), Integer.parseInt((String) map.get(“port”)));
// 设置登陆主机的密码
session.setPassword((String) map.get(“password”));// 设置密码
// 设置第一次登陆的时候提示,可选值:(ask | yes | no)
session.setConfig(“StrictHostKeyChecking”, “no”);
// 设置登陆超时时间
session.connect(300000);
} catch (JSchException e) {
e.printStackTrace();
}
Channel channel = null;
try {
channel = (Channel) session.openChannel("sftp");
channel.connect(10000000);
ChannelSftp sftp = (ChannelSftp) channel;//远程写入对象,ChannelSftp类是JSch实现SFTP核心类
String dirPath = "/dophystatic/files/"+perfix+"/" +contractId+"/";//存储路径
try {
sftp.cd(dirPath);//进入指定目录
} catch (SftpException e) {
sftp.mkdir(dirPath);//创建目录
sftp.cd(dirPath);//进入指定目录
}
OutputStream o = null;//写入流对象
String fileNames = files.getOriginalFilename();//文件名
o = sftp.put(fileNames);
o.write(files.getBytes());//写入流,这里注意:write()里放的一定是字节流,我的files是传入的参数MultipartFile files
o.close();
String HttpPrefixURL=iCommonConfigurationService.getUploadUrl();//上传URI
fileNames=HttpPrefixURL+"virtualUploadPath/"+perfix+"/"+contractId+"/"+fileNames;//存入数据库的路径+文件名,virtualUploadPath跳过shrio拦截访问到静态资源
object.put("fileNames",fileNames);
object.put("code",0);
} catch (Exception e) {
e.printStackTrace();
object.put("code", "fail");
} finally {
session.disconnect();
channel.disconnect();
}