VUE + PDF.js实现文件预览

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方法我用了一个定时器,如果不修改这个标题的话,打开的窗口的标题是一个随机的字符串,不是很美观。

有不足之处以及疑问之处请多多指教,感谢。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值