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();
}
}
最新评论
我的是ipv4网络,如何使用直播源啊!
我今天试了,不想啊,我的是新疆昌吉移动的网络。
收不到验证码电报
现在充值29起了