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();
}
}
最新评论
网飞没问题, 迪士尼+有解决方案么?
pp助手是安卓手机用的,根本下载用不来苹果
已解决
这样的话数据库里的结构为{"attachment":{"content":"xxx"}}, 要怎么才能变成{"content":"xxx"},从而使结构保持一致?
赞! make test不过的坑都写到的,谢谢楼主~
谢谢你
用了root用户还是一直502是怎么回事呢
student id 是空的