请求pdf文件流并进行预览

最近做了一个需求就是预览pdf等文件,不过后端返回的是一个文件流,需要前端做一定地处理才行。
我们来看一下具体的实现方式。预览pdf的插件使用的是pdf.js,具体请看这篇文章:pdf.js插件怎么控制工具栏的显示与隐藏

1、请求pdf文件流数据

先看一下请求pdf文件流的请求接口

getPdfStream(id,data,responseType = 'blob'){
    
    
   return request.get('/api/business/getPdfStream/'+id,{
    
    params:{
    
    ...data},responseType:responseType})
}
2、把请求回来的文件流数据转化为url
<template>
   <div>
     <iframe
        allowfullscreen="true"
        :src="contentUrl"
        frameborder="0"
        width="100%"
        height="1200px"
     ></iframe>
   </div>
</template>
<script setup>	
import {
    
    onMounted,ref} from 'vue'
let contentUrl = ref("")
let fileId = new URLSearchParams(location.hash.split("previewPdf?")[1]);
onMounted(()=>{
    
    
   getPdfContent(fileId)
})

// 获取pdf内容
function getPdfContent(fileId) {
    
    
   API.getPdfStream(fileId).then(res=>{
    
    
      // 这一步是关键,使用window.URL.createObjectURL把blob数据转为本地URL
      let url = window.URL.createObjectURL(new Blob([res.data]));
      
      contentUrl.value = `static/pdfjs/web/viewer.html?file=${
      
      url}`
   })
}
</script>

猜你喜欢

转载自blog.csdn.net/xiaolinlife/article/details/134602317
今日推荐