demand
The interface of WeChat applet to upload files to fastapi
Code
Frontend-WeChat Mini Program
Click upload-select a local album or take a photo
Note: url is an interface written by FastAPI, used to save files to the server (local here)
Important: pay attention to the naming of name: The function of this parameter is that the back-end can use this parameter to obtain the binary content of the picture, so this parameter should be consistent between the front and the back.
chooseImg: function () {
wx.chooseImage({
count: 1,
sourceType: ['album', 'camera'],
success(res) {
const tempFilePaths = res.tempFilePaths;
console.log(tempFilePaths[0]);
wx.uploadFile({
filePath: tempFilePaths[0],
url: 'http://127.0.0.1:8000/customer/auth/photo/upload',
header: {
'content-type': 'multipart/form-data',
'token': wx.getStorageSync('token')
},
name: "file",
success(res) {
console.log(res.data)
}
})
}
})
},
Backend-FastAPI
python -m pip install python-multipart // 上传文件的依赖
from fastapi import APIRouter, Header, File, UploadFile
Accept the parameter file to be the same as the front-end definition
@router.post("/customer/auth/photo/upload")
async def upload(file: UploadFile = File(...)):
filename = file.filename
temp = filename.split('.')
if temp[len(temp)-1] not in ["png", "jpg"]: # 不是png,jpg
return {
"code": 203, "msg": "不支持的图片格式"}
else:
try:
res = await file.read()
with open(filename, "wb") as f: # 文件会保存在跟服务器启动目录同一级
f.write(res)
return {
"code": 200, "msg": "上传成功"}
except Exception as e:
return {
"code": 201, "msg": "上传失败"}