iframe预览文件流

203 阅读1分钟
<iframe v-if="previewSrc" :src="previewSrc" frameborder="0" style="width: 100%; height: 770px"></iframe>

====================js=============================================
/**
* 新页面预览接口返回的pdf文件流
* @param {string} url 接口url
* @param {int} type 1为返回url对象,用于新页面除PDF外还有其它操作;2为直接打开新页面预览PDF
* @param {string} callBack 回调
*/
previewPdf (url, type = 1, callBack) {
    let xhr = new XMLHttpRequest()
    xhr.withCredentials = true
    xhr.open('get', url, true)
    xhr.setRequestHeader(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    xhr.responseType = 'blob'
    xhr.onload = function () {
        if (this.status === 200) {
            let changeUrl = ''
            let file = new Blob([this.response], { type: 'application/pdf' })
            if (window.createObjectURL !== undefined) { // basic
                changeUrl = window.createObjectURL(file)
            } else if (window.webkitURL !== undefined) { // webkit or chrome
                try {
                    changeUrl = window.webkitURL.createObjectURL(file)
                } catch (error) {

                }
            } else if (window.URL !== undefined) { // Mozilla (firefox)
                try {
                    changeUrl = window.URL.createObjectURL(file)
                } catch (error) {

                }
            }
            if (type === 1) {
                callBack && callBack(changeUrl)
            } else {
                let a = document.createElement('a')
                a.href = changeUrl
                a.target = '_blank'
                let evt = document.createEvent('MouseEvents')
                evt.initEvent('click', true, true)
                a.dispatchEvent(evt)
            }
        }
    }
    xhr.send()
},
// === 预览 ===
toPreview (id) {
    this.previewPdf(this.$basePath + '/riskSurveyHistory/currentRiskSurveyPdf/'+ id, 1, (changeUrl) => {
        this.previewSrc = changeUrl
        Object.assign(this.preview, {
            isShow: true,
            url: null
        })
        this.$nextTick(() => {
            this.loading = false
        })
    })
},