java实现文件图片上传至SFTP服务器

2021/9/7 9:36:15

本文主要是介绍java实现文件图片上传至SFTP服务器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

首先导入maven坐标依赖

        <!-- FTP工具类 -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>
        <!-- jcraft操作SFTP工具类-->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.54</version>
        </dependency>

然后创建一个实体类 用来写入服务器账号密码

package com.fosun.user.common.bean;

import lombok.Data;

@Data
public class SftpConfig {
    private String hostname="172.16.60.70";
    private Integer port=22;//  服务器默认端口一般不需要修改
    private String username="ceshi";
    private String password="z1LPevq25E!";
    private Integer timeout=6000;
    private String remoteRootPath;
    private String fileSuffix;
}

Controller层代码实现

package com.fosun.user.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fosun.user.bo.AccountBo;
import com.fosun.user.common.result.ReturnCodeEnum;
import com.fosun.user.entity.User;
import com.fosun.user.service.IUserService;
import com.fosun.util.result.ResultVO;
import com.fosun.util.token.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Api(description = "实名用户管理")
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private IUserService userService;

    @ApiOperation("图片写入到ftp服务器")
    @PostMapping(value = "/uploadPictures")
    public ResultVO uploadToAli(@RequestParam(value = "file", required = false) MultipartFile file) {
            String url;
        String name = file.getOriginalFilename();
        try {
            //获取图片扩展名
            String ext = name.substring(name.lastIndexOf(".") + 1);
            url = UUID.randomUUID().toString().replace("-", "") + "." + ext;
            SFTP sftp = new SFTP();
            SftpConfig sftpConfig = new SftpConfig();
            sftp.upload("/home/fosunuhi/resources/user", file.getInputStream(), url, sftpConfig);
            String imageUrl = "http://172.16.64.71:18081/user/" + url;
            return ResultVO.ok(imageUrl);
        } catch (Exception e) {
            return ResultVO.error();
        }
    }

}


SFTP工具类

package com.fosun.user.common.util;

import com.fosun.user.common.bean.SftpConfig;
import com.jcraft.jsch.*;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;


@Component
public class SFTP {
    private long count;
    /**
     * 已经连接次数
     */
    private long count1 = 0;

    private long sleepTime;

    /**
     * 连接sftp服务器
     *
     * @return
     */
    public ChannelSftp connect(SftpConfig sftpConfig) {
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(sftpConfig.getUsername(), sftpConfig.getHostname(), sftpConfig.getPort());
            Session sshSession = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getHostname(), sftpConfig.getPort());
            System.out.println("Session created ... UserName=" + sftpConfig.getUsername() + ";host=" + sftpConfig.getHostname() + ";port=" + sftpConfig.getPort());
            sshSession.setPassword(sftpConfig.getPassword());
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.setTimeout(sftpConfig.getTimeout());
            sshSession.connect();
            System.out.println("Session connected ...");
            System.out.println("Opening Channel ...");
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            System.out.println("登录成功");
        } catch (Exception e) {
            try {
                count1 += 1;
                if (count == count1) {
                    throw new RuntimeException(e);
                }
                Thread.sleep(sleepTime);
                System.out.println("重新连接....");
                connect(sftpConfig);
            } catch (InterruptedException e1) {
                throw new RuntimeException(e1);
            }
        }
        return sftp;
    }

    /**
     *
     * @param directory 路径
     * @param inputStream   上传流
     * @param name  文件名称
     * @param sftpConfig    配置
     */
    public void upload(String directory, InputStream inputStream,String name, SftpConfig sftpConfig) {
        ChannelSftp sftp = connect(sftpConfig);
        try {
            sftp.cd(directory);
        } catch (SftpException e) {
            try {
                sftp.mkdir(directory);
                sftp.cd(directory);
            } catch (SftpException e1) {
                throw new RuntimeException("ftp创建文件路径失败" + directory);
            }
        }
        try {
            sftp.put(inputStream, name);
        } catch (Exception e) {
            throw new RuntimeException("sftp异常" + e);
        } finally {
            disConnect(sftp);
            closeStream(inputStream, null);
        }
    }

    /**
     * 下载文件
     *
     * @param directory    下载目录
     * @param downloadFile 下载的文件
     * @param saveFile     存在本地的路径
     * @param sftpConfig
     */
    public void download(String directory, String downloadFile, String saveFile, SftpConfig sftpConfig) {
        OutputStream output = null;
        try {
            File localDirFile = new File(saveFile);
            // 判断本地目录是否存在,不存在需要新建各级目录
            if (!localDirFile.exists()) {
                localDirFile.mkdirs();
            }
            ChannelSftp sftp = connect(sftpConfig);
            sftp.cd(directory);

            output = new FileOutputStream(new File(saveFile.concat(File.separator).concat(downloadFile)));
            sftp.get(downloadFile, output);
            disConnect(sftp);
        } catch (Exception e) {
            throw new RuntimeException("文件下载出现异常,[{}]", e);
        } finally {
            closeStream(null, output);
        }
    }

    public void writeFileToRes(HttpServletResponse response, SftpConfig sftpConfig, String path) {
        InputStream inputStream = null;
        ServletOutputStream outputStream = null;
        try {
            ChannelSftp sftp = connect(sftpConfig);
            sftp.cd("\\EFT");
            sftp.cd("\\BANKSLIPS");
            sftp.cd("\\PDF");
            inputStream = sftp.get(path);
            byte[] buf = new byte[1024 * 10];
            outputStream = response.getOutputStream();
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(path, "UTF-8"));
            int readLength;
            while (((readLength = inputStream.read(buf)) != -1)) {
                outputStream.write(buf, 0, readLength);
            }
            outputStream.flush();
        } catch (SftpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeStream(null, outputStream);
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 下载远程文件夹下的所有文件
     *
     * @param remoteFilePath
     * @param localDirPath
     * @throws Exception
     */
    public void getFileDir(String remoteFilePath, String localDirPath, SftpConfig sftpConfig) throws Exception {
        File localDirFile = new File(localDirPath);
        // 判断本地目录是否存在,不存在需要新建各级目录
        if (!localDirFile.exists()) {
            localDirFile.mkdirs();
        }

        ChannelSftp channelSftp = connect(sftpConfig);
        Vector<ChannelSftp.LsEntry> lsEntries = channelSftp.ls(remoteFilePath);

        for (ChannelSftp.LsEntry entry : lsEntries) {
            String fileName = entry.getFilename();
            if (checkFileName(fileName)) {
                continue;
            }
            String remoteFileName = getRemoteFilePath(remoteFilePath, fileName);
            channelSftp.get(remoteFileName, localDirPath);
        }
        disConnect(channelSftp);
    }

    /**
     * 关闭流
     *
     * @param outputStream
     */
    private void closeStream(InputStream inputStream, OutputStream outputStream) {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean checkFileName(String fileName) {
        if (".".equals(fileName) || "..".equals(fileName)) {
            return true;
        }
        return false;
    }

    private String getRemoteFilePath(String remoteFilePath, String fileName) {
        if (remoteFilePath.endsWith("/")) {
            return remoteFilePath.concat(fileName);
        } else {
            return remoteFilePath.concat("/").concat(fileName);
        }
    }

    /**
     * 删除文件
     *
     * @param directory  要删除文件所在目录
     * @param deleteFile 要删除的文件
     * @param sftp
     */
    public void delete(String directory, String deleteFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 列出目录下的文件
     *
     * @param directory  要列出的目录
     * @param sftpConfig
     * @return
     * @throws SftpException
     */
    public List<String> listFiles(String directory, SftpConfig sftpConfig) throws SftpException {
        ChannelSftp sftp = connect(sftpConfig);
        List fileNameList = new ArrayList();
        try {
            sftp.cd(directory);
        } catch (SftpException e) {
            return fileNameList;
        }
        Vector vector = sftp.ls(directory);
        for (int i = 0; i < vector.size(); i++) {
            if (vector.get(i) instanceof ChannelSftp.LsEntry) {
                ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) vector.get(i);
                String fileName = lsEntry.getFilename();
                if (".".equals(fileName) || "..".equals(fileName)) {
                    continue;
                }
                fileNameList.add(fileName);
            }
        }
        disConnect(sftp);
        return fileNameList;
    }

    /**
     * 断掉连接
     */
    public void disConnect(ChannelSftp sftp) {
        try {
            sftp.disconnect();
            sftp.getSession().disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public SFTP(long count, long sleepTime) {
        this.count = count;
        this.sleepTime = sleepTime;
    }

    public SFTP() {
    }
}


这篇关于java实现文件图片上传至SFTP服务器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程