axios獲取圖片


 vue+tp5前后端分離項目,使用tp5驗證碼類,

 

return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/png');//最后返回的是png圖片

后台直接返回的是image文件格式,前端需要處理一下

方法一:

axios.get('/captcha', {
  params: param,
  responseType: 'arraybuffer'
})

.then(response => new Buffer(response.data, 'binary').toString('base64'))

.then(data => {
  $('#img').attr('src', data);
});

// 瀏覽器中好像沒有Buffer,改成這樣:
axios.get('/captcha', {
  params: param,
  responseType: 'arraybuffer'
})
.then(response => {
  return 'data:image/png;base64,' + btoa(
    new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), '')
  );
}).then(data => {
...
})

 原文鏈接https://segmentfault.com/q/1010000012407559

方法二(更為簡單):

html部分

<img :src="img" alt="驗證碼" title="點擊換一張" @click="getimg"/>
 
js部分
methods: {
  getimg () {
    this.img = this.img + '?num = ' + Math.random();//給圖片地址配一個無用的隨機數
  }
}
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM