通常前后端进行图片预览,要么后端直接给文件的具体url地址,要么给文件流,前端获取到文件流后进行相应处理。url地址就不多说不同格式的文件使用不同格式的标签,例如:img、video、object、embed、iframe等。本文实践讲的是服务端返回文件流前端处理:
方式1、blob转url
(1)请求头Accept设置期待的文件内容格式:developer.mozilla.org/zh-CN/docs/… 可参照该文档获取对应的accept格式
const headers = {
Accept: accept + ',text/plain,*/*'
}
(2)设置返回数据类型:responseType: 'blob'
(3)处理返回数据:将blod转url后,另外一个窗口预览
const blob = new window.Blob([res.data], {
type: accept + '; charset=utf-8'
})
const href = URL.createObjectURL(blob)
window.open(href, row.name, null, false)
URL.revokeObjectURL(href)
方式2、通过h5标签的形式展示
// 支持的文件格式:'png', 'jpg', 'jpeg', 'webp', 'jfif', 'pjpeg', 'pjp', 'gif', 'svg', 'webp', 'avif', 'apng', 'bmp', 'ico', 'cur',
previewImage(row) { // 预览图片
const imgWindow = window.open('')
const label = document.createElement('img')
label.src = xxx接口
imgWindow && imgWindow.document.body.appendChild(label)
},
previewVideo(row) { // 预览视频
const imgWindow = window.open('')
const label = document.createElement('video')
label.autoplay = true
label.loop = true
label.muted = true
label.playsinline = true
label.controls = true
const source = document.createElement('source')
source.src = xxx接口
source.type = 'video/mp4'
label.appendChild(source)
imgWindow && imgWindow.document.body.appendChild(label)
}
// 其他格式使用方法一