java后台Controller层代码

 @RequestMapping("downloadFile")
    public void downLoadFile(HttpServletRequest req, HttpServletResponse response) {
        String fileName = req.getParameter("fileName");
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
        byte[] buffer = new byte[1024 * 10];
        InputStream fis = null;
        BufferedInputStream bis = null;
        SFTPUtil sftp = null;
        try {
            sftp = new SFTPUtil(FtpUserName, FtpPassword, FtpServer,FtpPort);
            sftp.login();
            if (!sftp.isExist(receiptConfig.getRemoteDir(), fileName)) {
                throw new ServiceException("回单文件已被清理,请重新回单申请");
            }
            fis = sftp.download(receiptConfig.getRemoteDir() + fileName);
            bis = new BufferedInputStream(fis);
            ServletOutputStream out = response.getOutputStream();
            //读取文件流
            int len = 0;
            while ((len = fis.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            logger.error(e);
        } finally {
            sftp.logout();
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    bis = null;
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    fis = null;
                }
            }
        }
    }

SFTP工具类

public class SFTPUtil {
    private transient Logger log = Logger.getLogger(this.getClass());

    private ChannelSftp sftp;

    private Session session;
    /**
     * SFTP 登录用户名
     */
    private String username;
    /**
     * SFTP 登录密码
     */
    private String password;
    /**
     * 私钥
     */
    private String privateKey;
    /**
     * SFTP 服务器地址IP地址
     */
    private String host;
    /**
     * SFTP 端口
     */
    private int port;


    /**
     * 构造基于密码认证的sftp对象
     */
    public SFTPUtil(String username, String password, String host, int port) {
        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;
    }

    /**
     * 构造基于秘钥认证的sftp对象
     */
    public SFTPUtil(String username, String host, int port, String privateKey) {
        this.username = username;
        this.host = host;
        this.port = port;
        this.privateKey = privateKey;
    }

    public SFTPUtil() {
    }

    /**
     * 连接sftp服务器
     */
    public void login() {
        try {
            JSch jsch = new JSch();
            if (privateKey != null) {
                jsch.addIdentity(privateKey);// 设置私钥
            }

            session = jsch.getSession(username, host, port);

            if (password != null) {
                session.setPassword(password);
            }
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");

            session.setConfig(config);
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();

            sftp = (ChannelSftp) channel;
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接 server
     */
    public void logout() {
        if (sftp != null) {
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
        }
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }

    public boolean isExist(String serverPath, String folderName) {
        try {
            sftp.cd(serverPath);
            // 判断子目录文件夹是否存在,不存在即创建
            SftpATTRS attrs = null;
            attrs = sftp.stat(folderName);
            if (attrs != null) {
                return true;
            }

        } catch (Exception e) {
            e.getMessage();
            return false;
        }
        return false;
    }

    public boolean isConnect() {
        if (null != session) {
            return session.isConnected();
        }
        return false;
    }

    public InputStream download(String directory) throws SftpException {
        return sftp.get(directory);
    }

前端vue部分代码

window.location=process.env.BASE_API+"/member/downloadFile?fileName="+fileName ;

process.env.BASE_API+"/member/downloadFile?fileName="+fileName :服务端文件地址

process.env.BASE_API :服务端IP地址

response.data.result:服务端返回的文件名

receiptDownLoad(this.listQuery).then(response => {
                        if (response.data.code === 1) {
                            window.location=process.env.BASE_API+"/member/downloadFile?fileName="+response.data.result;
                        } else {
                            this.$message({title: '失败', message: response.data.result, type: 'error', duration: 2000});
                        }
                        this.listLoading = false;
                    });

前端页面显示结果:

在这里插入图片描述

之前是通过读取本地文件然后通过流的方式输出,后面因不需要存储本地就改为直接读sftp

读取本地文件代码:

 String fileName = req.getParameter("fileName");
        File file = new File(LocalDir+File.separator+fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024 * 10];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            ServletOutputStream out = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                out = response.getOutputStream();
                //读取文件流
                int len = 0;
                while ((len = fis.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        bis = null;
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        fis = null;
                    }
                }
            }
        }

该方法返回的是一个InputStream可以直接读;

fis = sftp.download(receiptConfig.getRemoteDir() + fileName);
Logo

前往低代码交流专区

更多推荐