The backend returns the Base64 file stream, and the frontend displays the file (PDF, Image)

background:

In actual development, the pdf file returned by the backend is returned to the frontend in the form of a base64 file stream. The front end needs to display the further processing of the file stream to the client.

1. Use VUE-PDF to preview files

To use the Vue-pdf plugin, you must first install it. Mentioned in my previous article. CMapReaderFactory can help deal with Chinese garbled characters.

<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)
})

2. Use Window.URL.createObjectURL to preview the file

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
})

I used pdf.js to do it according to the blogs of other friends before , but I kept reporting the error "PDF file is damaged". The operation steps are to download PDF.js from the official website, and place the two files in the static folder of the local project

 

 

Below is the code, please help to see where there is a problem

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));
    }
})

3. If the backend directly returns the PDF file address

Simply use window.open(url) and that's it. If it is on the ios side, you will encounter the problem of window.open failure. This is because ios has a strict security model; use window.location.href instead

Guess you like

Origin blog.csdn.net/codingLeader/article/details/123072783