图片服务器sftp

2020-04-07

1.引入依赖

	<!--sftp文件上传-->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.54</version>
        </dependency>

2.增加配置类

package com.laozhang.config;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "sftp")
@Component
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FileUploadConfig {

    private String ip;
    private String user;
    private String password;
    private int port;
    private String filepath;

}

3.增加工具类

package com.laozhang.utils;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.laozhang.config.FileUploadConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * @author 不忘初心
 * 本类用于文件上传的工具类
 */
@Component
public class FileUploadUtil {

    @Autowired
    private FileUploadConfig config;

    /**
     * 通过ssh链接服务器
     * sftp技术文件上传
     * @param bytes    文件字节流数组
     * @param fileName 文件名
     * @return
     * @throws Exception
     */
    public String sshSftp(byte[] bytes, String fileName) throws Exception {
        String ip = config.getIp();//上传文件的服务器地址
        String user = config.getUser();//连接服务器的用户名
        String password = config.getPassword();//密码
        int port = config.getPort();//端口号
        String filepath = config.getFilepath();//上传文件到服务器的文件路径
        Session session = null;
        Channel channel = null;
        JSch jsch = new JSch();
        if (port <= 0) {
            //连接服务器,采用默认端口
            session = jsch.getSession(user, ip);
        } else {
            //采用指定的端口连接服务器
            session = jsch.getSession(user, ip, port);
        }
        //如果服务器连接不上,则抛出异常
        if (session == null) {
            throw new Exception("session is null");
        }
        //设置登陆主机的密码
        session.setPassword(password);//设置密码
        //设置第一次登陆的时候提示,可选值:(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        session.connect(30000);
        OutputStream outstream = null;
        try {
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;
            //进入服务器指定的文件夹
            sftp.cd(filepath);
            //以下代码实现从本地上传一个文件到服务器,如果要实现下载,对换以下流就可以了
            outstream = sftp.put(fileName);
            outstream.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关流操作
            if (outstream != null) {
                outstream.flush();
                outstream.close();
            }
            if (session != null) {
                session.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
            return "http://" + ip + ":8081/images/" + fileName;
        }
    }

    /**
     * 将文件转换成byte数组
     * @param
     * @return
     */
    public static byte[] file2byte(File tradeFile){
        byte[] buffer = null;
        try
        {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }

}

4.yml配置

sftp:
  #服务器地址
  ip:  
  #服务器账号
  user:  
  #服务器密码
  password:  
  #SSH端口号
  port:  
  #上传到服务器的哪个路径
  filepath:
  #上传图片的大小
  servlet:
    multipart:
      max-file-size:  50MB
      max-request-size:  50MB

5.具体使用

    @Autowired
    private FileUploadUtil fileUploadUtil;

    private static byte[] BYTES = null;

    private static String URL = null;
if (logo != null && !logo.isEmpty()){
            try {
                BYTES = logo.getBytes();
            } catch (IOException e) {
                e.printStackTrace();
            }
            long l = System.currentTimeMillis();
            try {
                URL = fileUploadUtil.sshSftp(BYTES, l + "jpg");
                tenCustomProduct.setLogo(URL);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

标题:图片服务器sftp
作者:张范
地址:http://misterzhang.top/articles/2020/04/07/1586254049681.html