VUE + SpringBoot + PDF.js实现文件预览
下载pdf.js相关文件
点击此链接下载 pdf.js官网下载地址
下载完成后放入vue项目的static目录下:
build与web文件夹如图所示。
后端代码
控制层
@RequestMapping("/test")
public void er(HttpServletResponse response){
String path = "所需预览的文件存放的地址";// 如D:\\test.pdf
File file = new File(path);
response.setContentType("application/octet-stream");// 二进制流,不知道下载文件的类型
response.setHeader("content-type", "application/octet-stream");// 让服务器告诉浏览器它发送的数据属于什么文件类型
response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());// 设置文件名(这个信息头会告诉浏览器这个文件的名字和类型)\
OutputStream outputStream = null;// 文件输出流
try {
outputStream = response.getOutputStream();
} catch (IOException e) {
logger.error(e.getMessage());
}
FileDownLoad.fileReadInDownLoading(file, outputStream);
}
fileReadInDownLoading方法
public static void fileReadInDownLoading(File file, OutputStream outputStream) {
if (file.exists()) {
byte[] buffer = new byte[1024];
FileInputStream fis = null;// 文件输入流
BufferedInputStream bis = null;// 带缓冲区的输入流
OutputStream os = null;// 文件输出流
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
os = outputStream;
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new BaseException(PurchaseExceptionCode.下载错误);
} finally {
try {
if (bis != null) {
bis.close();
}
if (fis != null) {
fis.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
logger.error(e.getMessage());
throw new BaseException(PurchaseExceptionCode.下载错误);
}
}
}
}
没什么可说的就是把文件以流的方式返回给前端,下面看前端代码。
前端代码
api:
export function printOrderTag() {
return request({
url: '/prevview/test',
responseType: 'blob',
method: 'post'
})
}
调用该方法的js代码
将后端返回的字节流转化为url然后利用pdf.js在浏览器直接预览。
// 标签打印--预览
preview() { v
printOrderTag(params).then(data => {
const content = data
const blob = new Blob([content])
var url = window.URL.createObjectURL(blob)
this.pdfUrl = './static/pdf/web/viewer.html?file=' + encodeURIComponent(url)
var win = window.open(this.pdfUrl)
setTimeout(() => {
win.document.title = '标题' }, 500)
}).catch(response => {
console.log(response)
})
}
为了修改window.open打开窗口的标题,上面的js方法我用了一个定时器,如果不修改这个标题的话,打开的窗口的标题是一个随机的字符串,不是很美观。
有不足之处以及疑问之处请多多指教,感谢。