前言
前端上传图片,传到后端,然后后端直接把图片以image形式存入数据库,待前端请求时,再从数据库中取出,传给前端,逻辑上好像没什么问题,但是在实际操作过程中,前端获取到数据后并不能直接使用<img src=res.data/>
来显示图片
解决办法
- 在请求中,修改参数
responseType:"arraybuffer"
例如:
a. 使用axios进行修改,axios.get('http://xxxx.xxxx.xxx',{responseType:"arraybuffer"})
b. 使用xhr进行修改,xhr.responseType = 'arraybuffer'
- 修改返回值
const blob = new Blob([responseData], { type: imageType })
const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
- 引用
<img src={imageUrl}>
参考
JavaScript如何转换二进制数据显示成图片
Axios中文说明