请问一下微信小程序跟flask连接之后,如果函数里只是返回字符串success就没什么问题,但是我想写一个返回图片的代码就会500 internal error,有没有人知道为什么啊。能给一下在flask里写一个返回给微信小程序图片的代码吗,网上找了但是都会失败
微信小程序与 Flask 连接后,返回图片需要注意以下几点:
image/png
。send_file
函数。wx.request
函数请求图片,并设置 responseType
为 arraybuffer
。以下是一个简单的 Flask 返回图片的示例代码:
from flask import Flask, send_file
app = Flask(__name__)
@app.route('/image')
def get_image():
# 读取图片文件
with open('image.png', 'rb') as f:
image_data = f.read()
# 返回图片
return send_file(
io.BytesIO(image_data),
mimetype='image/png',
as_attachment=False,
attachment_filename='image.png'
)
在微信小程序中,可以使用以下代码请求图片:
wx.request({
url: 'http://your-flask-server/image',
responseType: 'arraybuffer',
success: function(res) {
// 将二进制数据转换为 base64 编码的字符串
var base64 = wx.arrayBufferToBase64(res.data);
// 在页面上显示图片
that.setData({
imageSrc: 'data:image/png;base64,' + base64
});
}
});
注意,上述代码中的 that
是指当前页面的 this
,imageSrc
是页面中用于显示图片的 image
标签的 src
属性。