demo.vue

1
2
3
<template>
<iframe src="src" width="100%" height="100vh" frameborder="none"></iframe>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { previewPdfSrc, getUrlObject } from '@/utils'
export default {
data(){
return {
src: ''
}
},
methods: {
getFileData(){
this.$axios({
url: 'demo/api',
method: 'post',
responseType: 'arraybuffer'
}).then( res => {
this.src = previewPdfSrc( res.data )
})
}
}
}

utils.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// params type ArrayBuffer
export function previewPdfSrc( fileArraybuffer ){
let blob = new Blob([fileArraybuffer], {
type: 'application/pdf;charset=utf-8'
})
// 将 arraybuffer 转换为 url对象
return getUrlObject( blob )
}

export function getUrlObject( blobFile ){
let url = null
if (window.createObjectURL !== undefined) { // basic
url = window.createObjectURL(blobFile)
} else if (window.webkitURL !== undefined) { // webkit or chrome
try {
url = window.webkitURL.createObjectURL(blobFile)
} catch (error) {
//
}
} else if (window.URL !== undefined) { // mozilla(firefox)
try {
url = window.URL.createObjectURL(blobFile)
} catch (error) {
//
}
}
return url
}