当我们上传附件的时候,还伴随这文件的预览的下载功能
文件预览
想实现文件预览首先,思考到显示图片而已,jquery ajax直接get请求 将返回data 赋值给img标签的src属性即可,but,普通的请求类型并不能请求成功
返回的数据是这种情况
原因 后端反我们的二进制流数据,需要xmlhttprequest 2 标准中支持流文件的,并且应该使用 xhr.response作为返回 而不是responseText。
// 发送get请求,接收后端返回的文件流
export function getFile(params, url) {
return request({
url: url,
method: 'get',
responseType: 'blob', //这是重点
params,
})
}
//调用接口
gets(id) {
getFile({ id: id }, '/common/preview').then(res => {
let src = window.URL.createObjectURL(res)//将查出的数据转换为图片路径
this.logpic = src;
this.imgVisible = true
}).catch(() => { })
},
上面只合适图片的,还可能想预览pdf格式的
getFile({ id: item.uid }, '/common/preview').then(res => {
const binaryData = [];
binaryData.push(res);
// console.log(binaryData);
//获取blob链接
var pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
window.open(pdfUrl);
// this.$router.push({ 'path': '/pdf', query: { url: Base64.encode(src) } })
}).catch(() => { })
},
无论后端返回的是图片还是pdf都能获取到,将获取的URL展示到页面
文件下载
与文件预览同理(关于有pdf的文件流接收)
downloadFile(item) {
getFile({ id: item.uid }, '/common/preview').then(res => {
const binaryData = [];
binaryData.push(res);
//获取blob链接
var pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
let a = document.createElement('a')
a.href = pdfUrl // 这里的请求方式为get,如果需要认证,接口上需要带上token
a.download = item.name
a.click()
this.$message.success('下载成功!')
}).catch(() => { })
}