使用uni-app開發webapp,由於后端返回的圖片文件是二進制文件流形式,前端展示需要轉換格式,首先想到的就是轉成base64進行展示,話不多說,直接填坑。
使用uni-app的uni.request進行網絡請求,在網上查找的資料是如果返回的是文件流需要設置responseType為‘bold’類型,uni-app官網文檔描述:設置響應的數據類型。合法值:text、arraybuffer。
故需要設置responseType為arraybuffer類型。
return request({ method: "GET", // 請求方式 url: platFormUrl+'/downFile.do', // 請求url responseType:'arraybuffer', data: data // 參數 })
請求拿到數據之后轉換成blod對象,blod對象轉base64
let blob = new Blob([res],{type: 'image/png'})
this.blobToDataURL(blob,(res)=>{
console.log(res)
})
blod對象轉base64方法
blobToDataURL(blob, callback) { let a = new FileReader(); a.onload = function(e) { callback(e.target.result); } a.readAsDataURL(blob); }