踩坑记录:本地磁盘的pdf转化成流,前端使用layer请求预览
在做这个需求的时候,虽说不难,但踩了不少坑,大概还是自己比较菜的原因,特意将其记载下来
首先,后端不需要引什么jar包,使用的都是io流,将所需要预览的图片,pdf等绝对路径赋值给path
下面贴一下后端代码:(Grovvy语言)
@RequestMapping(value = "pdfTest", method = RequestMethod.GET)
void pdfTest(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/pdf")
FileInputStream inputStream
OutputStream outputStream
try {
String path = "E://xx.pdf"
inputStream = new FileInputStream(new File(path))
outputStream = response.getOutputStream()
byte[] b = new byte[1024]
while ((inputStream.read(b)) != -1) {
outputStream.write(b)
}
} catch (IOException e) {
e.printStackTrace()
} finally { // 释放流
if (inputStream !=null){
inputStream.close()
}
if (outputStream !=null){
outputStream.flush()
outputStream.close()
}
}
}
前端需要自己去引layer的工具包,在这里我就不放了,自己百度,下面贴一下前端代码
previewFlow = "/test/pdfTest" //这## 标题个就是后端controller的地址,切记不要return
layer.open(
type: 2 //2是iframe标签,详细的还需自己去layer官方文档去看
,area: ['1200px', '720px']
,title : "pdf测试"
,closeBtn: true
,id: 1
,content: previewFlow
,maxmin: true
,btn: '关闭'
,btnAlign: 'c'
,shade: 0
,yes: () ->
layer.closeAll()
)
效果图:
下面贴一下layer官方文档网址:https://www.layui.com/doc/modules/layer.html#type