一、文件流转化图片
项目开发时,用到了wangEditor组件,有一个上传图片功能,调用上传图片接口后,无法进行插入,后调用下载接口,返回一个图网的文件流,转成blob,进行插入
1.wangEditor上传图片
(1)在请求下载接口时,直接请求blob类型
responseType: 'blob',
(2)接口返回文件流进行转化
downLoad(imgId).then(res => {
let url
url = window.URL.createObjectURl(res)
})
(3)然后直接使用插入图片的方法
insertImg(url)
2.页面初始化时直接下载图片进行展示
<img :src="baseUrl + '/download/api?imgId=' + imgId">
3.如果在页面无法进行转换,可以在获取列表数据后进行转换
this.dataList.map(item => {
item.img = this.handleChangeUrl(imgId)
})
async handleChangeUrl(imgId) {
let blob;
await downLoad(imgId).then(res => {
blob = response
})
return window.URl.createObjectURL(blob)
}
二、文件流下载
如果有需要,需要判断浏览器的
userAgent,以IE浏览器为例
myBrowser() {
const userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
const isOpera = userAgent.indexOf('Opera') > -1
if (userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera) {
return 'IE'
}
if (userAgent.indexOf('Trident') > -1) {
return 'Edge'
}
},
async handleDownLoadFile(fileId) {
await downLoadFile(fileId).then(res => {
const blob = new Blob([response], {
type: 'application/vnd.ms-excel' // 这边的类型需要改
})
// 兼容ie 下载文件
if (this.myBrowser() === 'IE' || this.myBrowser() === 'Edge') {
window.navigator.msSaveOrOpenBlob(blob, item.fileName)
return false
}
const blogUrl = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.style.display = 'none'
link.download = item.fileName // 这边的名字需要改
link.href = blogUrl
document.body.appendChild(link)
link.click()
}).catch(() => {})
},
如需转载,请注明出处和作者!