Java 结合layui 实现文件预览功能
开发中遇到的一个需求,记录下实现方式
通过将文件转成pdf 文件实现对文件的预览功能以及下载
下面是实现的代码
/**
* 文件预览接口
*/
@GetMapping(value = "/pdf/review")
public ResponseEntity<?> pdfReview(@Param("fileName") String fileName) throws IOException {
// 获取文件上传的路径
String filePath = appProperties.getUploadPath();
// 判断文件是不是word
if (fileName.contains(".doc") || fileName.contains(".docx")) {
String[] name = fileName.split("\\.");
fileName = name[0] + ".pdf";
}
File file = new File(filePath + "/" +fileName);
try (FileInputStream fileInputStream = new FileInputStream(file)) {
byte[] buf = new byte[fileInputStream.available()];
fileInputStream.read(buf);
return HttpUtil.getResponseEntity(buf, "inline", file.getName());
}
}
前端代码
触发事件
通过点击事件触发文件预览,调用【showFile】方法
table.on('tool(currentTableId_pw)', function (obj) {
if (obj.event === "view_detail") {
openEdit('查看信息', 'sjtjEdit?mode=view&code=' + code + '&objId=' + obj.data.objId, '80%', '80%');
return false;
}
// 文件预览
if (obj.event === "file_download") {
let fileName = obj.data.pdUpFile
if (fileName != null && fileName != '') {
// 23.46.161.226
showFile("http://localhost:18001/kspwgc/ks/fileApi/pdf/review?fileName="+ fileName, "文件预览", fileName, true, true)
} else {
layer.msg("文件下载地址为空!")
}
}
});
- showFile 方法
url:文件预览接口
fileName:文件名称
isDownload: 是否下载 (true, false)(文件下载接口在文章下面)
var showFile = function (url, title, fileName, isDownload) {
if(!title || title === "") title = "文件";
console.log(url);
let btnArry = ['已阅'];
if(isDownload) {
btnArry.push('下载');
}
layer.open({
type: 1
,title: title
,area: ['80%', '600px']
,shade: 0.5
,scrollbar: false
,maxmin: true
,cancel: function(index, layero){
layer.close(index)
}
,offset: [
-($(window).height() * 0.02)
,($(window).width() * 0.2)
]
,content: '<iframe src="' + url + '" style="width: 99%; height: 99%;"></iframe>'
,btn: btnArry
,yes: function(){
layer.closeAll();
}
,btn2: function(){
download(fileName);
}
,zIndex: layer.zIndex //重点1
,success: function(layero){
let btn = layero.find('.layui-layer-btn').find('.layui-layer-btn1');
btn.attr({class: 'layui-btn layui-btn-normal',
style: 'background-color: #1E9FFF!important;',
});
}
});
}
文件下载
后端接口
该方法是根据文件名称下载文件
/**
* 文件下载
* @param request
* @param response
*/
@RequestMapping(value = "/downloadToClient")
public void downloadToClient(HttpServletRequest request, HttpServletResponse response, @RequestParam("fileName") String fileName) {
String filePath = appProperties.getDownloadPath();
if (StringUtils.isEmpty(fileName)) {
log.error("文件名称为空!");
return;
}
String filePathName = filePath + fileName;
BufferedInputStream bins = null;
BufferedOutputStream bouts = null;
try {
//同一个窗口下载多次,清除空白流
response.reset();
File file = new File(filePathName);
if (!file.exists()) {
log.error("要下载的文件不存在:{}", filePathName);
return;
}
bins = new BufferedInputStream(new FileInputStream(filePathName));
bouts = new BufferedOutputStream(response.getOutputStream());
String userAgent = request.getHeader("USER-AGENT").toLowerCase();
// 如果是火狐浏览器
if (userAgent.contains("firefox")) {
fileName = new String(fileName.getBytes(), "ISO8859-1");
} else {
fileName = URLEncoder.encode(fileName, "UTF-8");
}
//设置发送到客户端的响应的内容类型
response.setContentType("application/download");
//指定客户端下载的文件的名称
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
int len;
byte[] bytes = new byte[1024];
while ((len = bins.read(bytes)) != -1) {
bouts.write(bytes, 0, len);
}
//刷新流
bouts.flush();
log.info("下载完成");
} catch (IOException e) {
log.error("下载文件异常:{}", e.getMessage());
e.printStackTrace();
} finally {
try {
if (bouts != null) {
bouts.close();
}
if (bins != null) {
bins.close();
}
} catch (IOException e) {
log.error("关闭流异常", e);
e.printStackTrace();
}
}
}
前端
var download = function (fileName) {
var hiddenLink = document.createElement('a');
hiddenLink.href = "ks/fileApi/downloadToClient?fileName=" + fileName; // 设置下载接口的URL
hiddenLink.style.display = 'none';
document.body.appendChild(hiddenLink);
// 触发a标签的点击事件以开始下载文件
hiddenLink.click();
// 移除隐藏的a标签
document.body.removeChild(hiddenLink);
}