springboot+sftp实现文件远程上传

策略:

1.环境(centos7系统),作为 ftp文件服务器

2.使用nginx,作为静态资源文件服务器,来进行访问

一、引入依赖

      <!-- Sftp工具 -->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.54</version>
        </dependency>

二、配置文件

#上传文件到文件服务器的配置
ftp-server:
  #IP
  host: 主机
  #端口
  port: 22
  user: sftp
  password: sftp
  #文件目录
  basePath: /home/sftp/resources/

三、SftpClientUtil(sftp客户端工具类)

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;


public class SftpClientUtil {

    /** Sftp */
    private ChannelSftp sftp = null;
    /** 主机 */
    private String host = "";
    /** 端口 */
    private int port = 0;
    /** 用户名 */
    private String username = "";
    /** 密码 */
    private String password = "";

    /**
     * 构造函数
     *
     * @param host
     *            主机
     * @param port
     *            端口
     * @param username
     *            用户名
     * @param password
     *            密码
     *
     */
    public SftpClientUtil(String host, int port, String username, String password)
    {

        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    /**
     * 连接sftp服务器
     *
     * @throws Exception
     */
    public void connect() throws Exception
    {

        JSch jsch = new JSch();
        Session sshSession = jsch.getSession(this.username, this.host, this.port);

        sshSession.setPassword(password);
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        sshSession.connect(20000);

        Channel channel = sshSession.openChannel("sftp");
        channel.connect();
        this.sftp = (ChannelSftp) channel;
    }

    /**
     * Disconnect with server
     *
     * @throws Exception
     */
    public void disconnect() throws Exception
    {
        if (this.sftp != null)
        {
            if (this.sftp.isConnected())
            {
                this.sftp.disconnect();
            } else if (this.sftp.isClosed())
            {
            }
        }
    }

    /**
     * 下载单个文件
     *
     * @param directory
     *            下载目录
     * @param downloadFile
     *            下载的文件
     * @param saveDirectory
     *            存在本地的路径
     *
     * @throws Exception
     */
    public void download(String directory, String downloadFile, String saveDirectory) throws Exception
    {
        File pathFile = new File(saveDirectory);
        if (!pathFile.exists())
        {
            pathFile.mkdirs();
        }

        String saveFile = saveDirectory + "//" + downloadFile;

        this.sftp.cd(directory);
        File file = new File(saveFile);
        this.sftp.get(downloadFile, new FileOutputStream(file));
    }

    /**
     * 下载目录下全部文件
     *
     * @param directory
     *            下载目录
     *
     * @param saveDirectory
     *            存在本地的路径
     *
     * @throws Exception
     */
    public void downloadByDirectory(String directory, String saveDirectory) throws Exception
    {
        String downloadFile = "";
        List<String> downloadFileList = this.listFiles(directory);
        Iterator<String> it = downloadFileList.iterator();

        while (it.hasNext())
        {
            downloadFile = it.next().toString();
            if (downloadFile.toString().indexOf(".") < 0)
            {
                continue;
            }
            this.download(directory, downloadFile, saveDirectory);
        }
    }

    /**
     * 新建子目录
     *
     * @param dst 远程服务器路径
     *
     * @throws Exception
     */
    public void mkdir(String dst, String subDir) throws Exception
    {

        this.sftp.cd(dst);
        try {
            if(this.sftp.ls(subDir).size() > 0) {
                return;
            }
        } catch (SftpException se) {
        }

        this.sftp.mkdir(subDir);
    }

    /**
     * 上传单个文件
     *
     * @param src 文件
     * @param dst 远程服务器路径
     *
     * @throws Exception
     */
    public void upload(InputStream src, String dst) throws Exception
    {
        this.sftp.put(src, dst);
    }

    /**
     * 列出目录下的文件
     *
     * @param directory
     *            要列出的目录
     *
     * @return list 文件名列表
     *
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public List<String> listFiles(String directory) throws Exception
    {

        Vector fileList;
        List<String> fileNameList = new ArrayList<String>();

        fileList = this.sftp.ls(directory);
        Iterator it = fileList.iterator();

        while (it.hasNext())
        {
            String fileName =((LsEntry) it.next()).getFilename();
            if (".".equals(fileName) || "..".equals(fileName))
            {
                continue;
            }
            fileNameList.add(fileName);

        }

        return fileNameList;
    }

    /**
     * 删除目标文件
     * @param dst
     */
    public void delete(String dst) throws SftpException {
            this.sftp.rm(dst);
    }


    /**
     * 迁移目标文件
     *
     * @return
     */
    public void update(String src, String dst, String fileName) throws SftpException {
            if(!isExistDir(dst)){
            this.sftp.mkdir(dst);
        }
        System.out.println(src+"/"+fileName);
        this.sftp.rename(src + "/" + fileName, dst + "/" + fileName);
    }

    /**
     * 判断目录是否存在
     * @param path
     * @return
     */
    public boolean isExistDir(String path){
        boolean  isExist=false;
        try {
            SftpATTRS sftpATTRS = this.sftp.stat(path);
            isExist = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isExist = false;
            }
        }
        return isExist;

    }

    public ChannelSftp getSftp()
    {
        return sftp;
    }

    public void setSftp(ChannelSftp sftp)
    {
        this.sftp = sftp;
    }
}

四、FileUtil(文件业务工具类)

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.jcraft.jsch.SftpException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Component
public class FileUtil {

    public static final String videoDir = "video";
    public static final String imagesDir = "images";
    public static final String pdfDir = "pdf";
    public static final String indexDir = "images/index";

    /** 主机 */
    @Value("${ftp-server.host}")
    private String host;
    /** 端口 */
    @Value("${ftp-server.port}")
    private int port;
    /** 用户名 */
    @Value("${ftp-server.user}")
    private String user;
    /** 密码 */
    @Value("${ftp-server.password}")
    private String password;
    /** 存放路径 */
    @Value("${ftp-server.basePath}")
    private String basePath;

    public String upload(MultipartFile file,String fileParentDir){
        if (file.isEmpty()) {
          //  throw new ApiException("文件为空");
        }
        String url = newName(file);
        SftpClientUtil sftp = new SftpClientUtil(host, port, user, password); //初始化
        try {
            sftp.connect();  //连接
        } catch (Exception e) {
         //   throw new ApiException("连接sftp服务器失败");
        }

        try {
            String[] split = fileParentDir.split("/");
            String tempV = basePath;
            for (int i = 0; i < split.length; i++) {
                sftp.mkdir(tempV, split[i]);
                tempV = tempV+"/"+split[i];
            }
            sftp.upload(file.getInputStream(),tempV+"/"+url);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                sftp.disconnect();
            } catch (Exception e) {
             //   throw new ApiException("关闭sftp服务器失败");
            }
        }


        return url;
    }

    /**
     * 为文件获取新的文件名
     *
     * @return
     */
    public String newName(MultipartFile file) {
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf(StrUtil.C_DOT));  // 后缀名
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        return fileName;
    }


    /**
     * 删除文件
     */
    public void deleteFile(String dst){
        SftpClientUtil sftp = new SftpClientUtil(host, port, user, password); //初始化
        try {
            sftp.connect();  //连接

        } catch (Exception e) {
         //   throw new ApiException("连接sftp服务器失败");
        }

        try {
            sftp.delete(basePath+dst);
        } catch (SftpException e) {
            e.printStackTrace();
        }

        try {
                sftp.disconnect();
            } catch (Exception e) {
            //    throw new ApiException("关闭sftp服务器失败");
            }

    }

    /**
     * 移动文件
     */
    public void update(String src,String dst,String fileName){
        SftpClientUtil sftp = new SftpClientUtil(host, port, user, password); //初始化
        try {
            sftp.connect();

        } catch (Exception e) {
            e.printStackTrace();
          //  throw new ApiException("连接sftp服务器失败");
        }


        try {
            sftp.update(basePath+src,basePath+dst,fileName);
        } catch (SftpException e) {
            e.printStackTrace();
        }
        try {
                sftp.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
             //   throw new ApiException("关闭sftp服务器失败");
            }

    }
}

五、资源访问

1.安装nginx https://blog.csdn.net/curru/article/details/110954779

2.修改目录

 vim /etc/nginx/nginx.conf 
 
 修改此处
 #######
    location / {
            root   /home/sftp/resources/;
            index  index.html index.htm;
        }
 #######       
 
 修改完要重启nginx
 systemctl restart nginx

3.就可以直接通过

​ http://域名/文件进行访问了

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值