FastAPI-微信小程序上传图片到服务器

it2024-03-12  74

需求

微信小程序上传文件到fastapi的接口

Code

前端-微信小程序

点击上传-选择本地相册或者拍照

注意点:url为FastAPI写的接口,用于保存文件到服务器(此处为本地)

重点:注意name的命名:这个参数的作用是后端可以用这个参数获得图片的二进制内容,因此这个参数,前后端要一致。

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) } }) } }) },

后端-FastAPI

python -m pip install python-multipart // 上传文件的依赖

from fastapi import APIRouter, Header, File, UploadFile

接受参数file要与前端定义的相同

@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": "上传失败"}
最新回复(0)