vue 或者 uniapp H5 项目中,前端回显接口返回的文件流附件
...大约 1 分钟
vue 或者 uniapp H5 项目中,前端回显接口返回的文件流附件
背景
正在做一个考核管理系统,需要用到附件的上传以及回显。项目有 vue 做的 pc 端,以及 uniapp 做的 H5 移动端,做的时候发现二者的回显稍有不同,记录一下。因为附件只牵扯到 pdf 和图片,所以只写了这两种的回显。
1、vue 项目中回显
function reviewFile (file) {
let fileType = ''
if (file.fileName.indexOf('.pdf') != -1) {
fileType = 'application/pdf'
} else {
fileType = 'image/png'
}
axios({
url: process.env.VUE_APP_BASE_URL + '/file/download/' + file.file,
method: 'get',
responseType: 'blob', // 一定要设置响应类型为 blob
headers: { token: token } // 对于有鉴权的接口,需要添加token
}).then(res => {
// 创建用于作为附件预览源的Blob
const blob = new Blob([res.data], { type: fileType });
// 创建用于作为PDF预览源的Blob的URL
let url = URL.createObjectURL(blob);
window.open(url)
})
},
2、uniapp H5 项目中回显
function reviewFile (file) {
let fileType = ''
if (file.fileName.indexOf('.pdf') != -1) {
fileType = 'application/pdf'
} else {
fileType = 'image/png'
}
uni.request({
url: getApp().globalData.baseUrl + '/file/download/' + file.file,
method: 'get',
responseType: 'arraybuffer', // 这里跟vue项目有所区别,响应格式为 arraybuffer
header: { token: getApp().globalData.Authorization } // 对于有鉴权的接口,需要添加token
}).then(res => {
// 创建用于作为附件预览源的Blob
// 打印发现,数据存放在 res[1].data 中
const blob = new Blob([res[1].data], { type: fileType });
// 创建用于作为PDF预览源的Blob的URL
let url = URL.createObjectURL(blob);
window.open(url)
})
},