vue文件下載,java讀取SFTP文件通過流的方式輸出到前端

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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章