SpringBoot实现FTP文件下载及预览功能

洼地云 tuoyidashi.png

SpringBoot将文件上传到FTP之后,后续的在前端进行文件的下载及预览实现方式如下:

前端代码

// 根据文件路径和文件名进行下载
function downLoadFile(filePath, fileName) {
    // 后台获取文件
    var url = "/data-query/uploadfileinfo/downloadByPath?filePath=" + filePath + "&fileName=" + fileName;
    var xmlHttpRequest = new XMLHttpRequest();

    xmlHttpRequest.open("POST", url);
    xmlHttpRequest.responseType = 'blob';
    xmlHttpRequest.setRequestHeader('Authorization', layui.sessionData("checkModel").Authorization);
    xmlHttpRequest.onreadystatechange = function () {
        if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
            var blob = new Blob([xmlHttpRequest.response]);
            var csvUrl = URL.createObjectURL(blob);
            var link = document.createElement('a');
            link.href = csvUrl;
            link.click();
        }
    };
    xmlHttpRequest.send();
}

// 根据文件路径和类型进行预览
function viewFtpFile(filePath, fileType){
    if (fileType == 'pdf'){
        // 后台获取文件流
        var fileStream = '/uploadfileinfo/viewFtpFile/?filePath=' + filePath;
        // 使用Mozilla pdf.js进行预览
        window.location.href = "/html/pdfjs/web/viewer.html?file=" + encodeURIComponent(fileStream);
    }
}

后台实现

1.后台FTP获取文件方法

@PostMapping(value = "/downloadByPath")
public void downloadByPath(HttpServletRequest req, HttpServletResponse resp, @RequestParam("filePath") String filePath) {
    uploadFileInfoService.downloadByPath(req, resp, filePath);
}


public void downloadByPath(HttpServletRequest req, HttpServletResponse resp, String fileFullPath) {
    String filePath = fileFullPath.substring(0, fileFullPath.lastIndexOf("/"));
    String fileName = fileFullPath.substring(fileFullPath.lastIndexOf("/") + 1);
    try {
        FtpUtils ftpUtil = new FtpUtils(hostname, port, username, password);
        boolean flag = ftpUtil.initFtpClient();
        if (!flag) {
            System.out.print("ftp服务器连接失败.....");
        } else {
            byte[] b = ftpUtil.downloadFile(filePath, fileName);
            jwQueryApplyService.downLoadFile(req, resp, b, fileName);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
赞(0)
未经允许禁止转载:优米格 » SpringBoot实现FTP文件下载及预览功能

评论 抢沙发

合作&反馈&投稿

商务合作、问题反馈、投稿,欢迎联系

广告合作侵权联系

登录

找回密码

注册