?先亮结果:
小程序端:
服务器端:
详细代码:
博文仅针对这一个功能,其它的比如wxml和wxss设置,或者微信昵称的获取就不多介绍了。
找了很久也没有找到真实的图片链接地址的获取方式。。。如果有大佬知道如何弄,还请评论区指条明路。
本文用base64代替真实头像地址。后端有python和golang两种方式,供学习参考。
前端:
(不知道这个临时头像地址什么时候失效,改成你刚刚获取的临时地址,也就是下面代码的这一行换掉:
?filePath: 'http://tmp/OYjz9xgN3sbZd18874aba0c54e580629f9df5623e3d9.jpeg',)
Page({
onLoad() {
wx.uploadFile({
url: 'http://127.0.0.1:8080/upload',
filePath: 'http://tmp/OYjz9xgN3sbZd18874aba0c54e580629f9df5623e3d9.jpeg',
name: 'file',
success: function (res) {
const responseData = JSON.parse(res.data);
console.log(responseData.base64_data);
}
});
},
});
python后端:
(关闭其它进程,确保8080端口没被占用)
import base64
from io import BytesIO
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload_file():
try:
uploaded_file = request.files['file']
# 读取上传的文件并转换为 Base64 编码
with BytesIO() as buffer:
uploaded_file.save(buffer)
base64_data = base64.b64encode(buffer.getvalue()).decode('utf-8')
print(base64_data)
# 返回 Base64 编码给前端
return jsonify({"message": "Upload successful!", "base64_data": base64_data})
except Exception as e:
return jsonify({"error": str(e)})
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080)
golang后端:
(关闭其它进程,确保8080端口没被占用)
import base64
from io import BytesIO
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload_file():
try:
uploaded_file = request.files['file']
# 读取上传的文件并转换为 Base64 编码
with BytesIO() as buffer:
uploaded_file.save(buffer)
base64_data = base64.b64encode(buffer.getvalue()).decode('utf-8')
print(base64_data)
# 返回 Base64 编码给前端
return jsonify({"message": "Upload successful!", "base64_data": base64_data})
except Exception as e:
return jsonify({"error": str(e)})
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080)