vue:前端接收并展示后端返回的一个图片对象(文件流) |
您所在的位置:网站首页 › js如何接收返回的图片 › vue:前端接收并展示后端返回的一个图片对象(文件流) |
需求:
前端接收并展示后端返回的一个图片对象(文件流),没有图片的时候,显示默认图片。 1. HTML造空间,展示图片 2. 定义变量这里require的作用是设置默认图片。 data () { return { qrcodeSrc: require('@/assets/images/img_empty.png') } }, 3. 定义请求的接口重点是添加 responseType: 'blob',表明这是个blob对象。 不加这个类型,会报错TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'. (定义接口的形式类似,取决于自己如何封装接口) getQrcode: { url: '/xxxxxx/qrcode', // 请求接口的路径 method: 'get', // 请求方法 responseType: 'blob', // response类型 params: {} // 入参 }, 4. 请求接口并赋值URL.createObjectURL() 静态方法会创建一个 DOMString,其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。 getData() { this.Api.getQrcode({ // 请求刚刚定义的接口 params: { // 入参 name: '奶绿走糖', id: '9999' } }).then(res=>{ // 获取返回参数res let url = window.URL.createObjectURL(res.data); // 获取对象url this.qrcodeSrc = url // 给变量赋值 }) }另一种写法 async getData() { let params = { name: '奶绿走糖', id: '9999' } let res = await this.Api.getQrcode(params) // 获取后盾返回的参数res let url = window.URL.createObjectURL(res.data); // 获取返回参数中的需要的值data this.qrcodeSrc = url // 把获取到的值,赋值给变量qrcodeSrc } |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |