后端返回二进制流,前端处理二进制文件流,实现预览图片以及PDF

1、首先预览PDF需要后端将响应头Content-Type 设置为PDF类型application/pdf,不能预览,会直接下载

2、前端定义接口:并设置相应类型responseTypeblob

// 合同预览Pdf
export function viewContractTypePdf(id) {
  return request({
    url: `/attract/talentApartment/exportContract/${id}`,
    method: "get",
    responseType: "blob"
  })
}

  1. 请求数据:通过window.URL.createObjectURL(res)转成本地预览地址, 在通过window.open()方法打开转成本地预览地址即可预览PDF,如下图

图一

  1. 预览图片:直接将window.URL.createObjectURL(res)转成的本地预览地址赋值给Img的src即可展示图片

// vue中
// template
<el-image :src="imgUrl" fit="fill" ></el-image>


//methods
handleViewPDF() {
   viewContractTypePdf(this.baseInfo.talentId).then(res => {
     this.imgUrl = window.URL.createObjectURL(res)
   })
}

猜你喜欢

转载自blog.csdn.net/snows_l/article/details/129170798