从本地向远程Linux服务器写入文件

公司系统中上传功能不合理场景: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();
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值