众所周知,以字典新式返回response需要进行序列化,而图片的字节流bytes无法进行序列化,需要将其转化为字符串。所以我们可以将图片进行base64编码,后端代码具体如下
import base64
@app.route('function', methods=['GET', 'POST'])
def function():
with open('res.jpg', 'rb') as f:
img_byte = f.read() #二进制编码
img_b64 = base64.b64encode(img_byte) #img_b64是字节类型变量,b64.encode()对字节类型变量进行b64编码,bytes->bytes
img_res = img_b64.decode('utf-8') #相当于去掉字符串前面的b'....'
return {'res':img_res}
前端代码如下(vue):
<el-image
v-show="true"
:src="resultsrc"
style="text-align: center; width: 230px; height: 230px;"
/>
axios.post('api',
formData
).then((response) => {
if (response.status === 'ok') {
console.log('上传成功')
}
#'data:image/jpeg;base64,'+ 你的base64编码; .res对应key
const src = 'data:image/jpeg;base64,' + response.data.res
this.resultsrc = src
this.resvisible = true
)