preview pdf using iframe

This article mainly introduces the function of using iframe to preview pdf, as well as the iframe preview error report and iframe failure to load the PDF document.
The preview comes with pagination, download, rotation, scale and other functions.
insert image description here
1. What is an iframe?
Introduction to iframe: Display the content of src in the frame.
The iframe can be used to preview the documents under the local static, and also can preview the file stream documents returned by the backend.
2. Use steps
1. Use and logic:

逻辑:就是将后端返回的看不懂的文件流,设置成responseType = 'blob'然后读取到返回的Blob,再使用createObjectURL读取出url即可
对于后缀名是大写的.PDF 没法直接预览,建议直接下载下来看
 <iframe  :src="url" style="border: none;width: 100%;height: 100%;">
     <p>您的浏览器不支持 iframe 标签,请从列表中下载预览</p>
 </iframe>



  data () {
    
    
    return {
    
    
      url: '',
      }
  },
  methods: {
    
    
   downLoadFileImg (fileUrl, fileName) {
    
    // 后端文件地址和名称
      

      // 可下载,名称也有效 -- 推荐
      const x = new window.XMLHttpRequest()
      x.open('GET', fileUrl, true)
      x.responseType = 'blob' // 选择返回格式为blob --- 一般后端返回的是看不懂的文件流 故需要转成blob
      x.onload = () => {
    
    
        this.url = window.URL.createObjectURL(x.response) //将后端返回的blob文件读取出url
		
		console.log('blob====',x.response)   //Blob {size: 38617, type: 'application/pdf'}
		console.log('url====',this.url)   //blob:http://localhost:7197/cb047277-e5e6-4905-bf8c-dbecd86a0105

		// url可以预览和下载------如果想要下载就把下方注释打开即可
        // const a = document.createElement('a')
        // a.href = this.url
        // a.download = fileName
        // a.click()
      }
      x.send()



      // // 或者下方的方式
      // axios({
    
    
      //   url: G_CGI_PHP.superOrder.upfile + "?id=" + this.rowData.id,
      //   method: 'get',
      //   timeout: 100000,
      //   responseType: 'blob',
      //   headers: {
    
    
      //     // "type": 'application/pdf'
      //   },
      // }).then(res => {
    
    
      //   console.log('res.data', res.data)
      //   this.url = window.URL.createObjectURL(res.data) //将后端返回的blob文件读取出url
      //   console.log('通过读取blob文件得到url地址===', this.url)
      // }).catch(error => {
    
    
      //   console.log(error)
      // })


    },

  }

2. Graphic and text detailed explanation:
insert image description here
insert image description here
3. Error situation:
insert image description here
insert image description here
Reason: It means that what you read in createObjectURL is not the blob obtained after setting responseType: 'blob', it may be the incomprehensible file stream res returned by the directly read backend

Guess you like

Origin blog.csdn.net/m0_49515138/article/details/128611758