后端返回Base64文件流,前端显示文件(PDF、Image)

背景:

在实际开发中,后端返回的pdf文件,是以base64文件流的方式,返回给前端。前端需要将文件流进一步处理展示给客户。

一、使用VUE-PDF预览文件

使用Vue-pdf插件,首先要安装。在我之前的文章有提到。CMapReaderFactory可以帮助处理中文乱码的问题。

<template>
    <pdf v-for="i in numPages" :key="i" :src="src" :page="i" ref="PDFDom"></pdf>
</template>

import pdf from 'vue-pdf'
import CMapReaderFactory from 'vue-pdf/src/CMapReaderFactory.js'

getCarElectronicInfo({policyNo: this.policyNo}).then(res => {
    if(res.status == '0' && res.data) {
        let datas = 'data:application/pdf;base64,' + res.data.result //后端返回的文件流
        this.src = pdf.createLoadingTask({
		    url: datas,
			CMapReaderFactory
		});
        this.src.promise.then(pdf => {
		    this.numPages = pdf.numPages;
		});
    }
    
}).catch(error =>{
    console.log(error)
})

二、使用Window.URL.createObjectURL预览文件

getCarElectronicInfo({policyNo: this.policyNo}).then(res => {
    var binaryData = [];
    binaryData.push(res.data.result);
    var bolb = new Blob(binaryData, {type: "application/pdf"});
    var fileUrl = null;
    // 区分浏览器
    if (window.createObjectURL != undefined) { 
       fileURL = window.createObjectURL(blob)
    }else if(window.webkitURL != undefined){
        try {
            fileURL = window.webkitURL.createObjectURL(blob);
        }
    }else if(window.URL != undefined) {
        fileURL = window.URL.createObjectURL(blob);
    }
    let url= encodeURIComponent(fileURL)
    windoe.location.href = url
})

之前按照其他小伙伴的博客,使用pdf.js也做了一下但一直报错“PDF文件已损坏”。操作步骤是官网下载PDF.js,将其中的俩个文件,放置到本地项目的static文件夹下

 

下边是代码,请各位帮忙看下那里有问题

getCarElectronicInfo({policyNo: this.policyNo}).then(res => {
    if(res.status == '0' && res.data) {
        var binaryData = [];
        binaryData.push(res.data.result);
        this.url = window.URL.createObjectURL(new Blob(binaryData,{type:"application/pdf"}));
        window.open('/static/pdf/web/viewer.html?file=' +encodeURIComponent(this.url));
    }
})

三、如果后端直接返回PDF文件地址

简单粗暴的使用window.open(url),即可。如果在ios端,会遇到window.open失效的问题。这是因为ios有严格的安全模式;可用window.location.href代替

猜你喜欢

转载自blog.csdn.net/codingLeader/article/details/123072783