为了方便调试el-upload,使用FastApi写的上传图片接口demo

2 阅读1分钟

在使用Element Plus的Upload组件的时候,必须写一个可以调通的接口,因为后端没有开发完成,所以就使用FastApi写了个小demo,自己设置好origins允许的跨域来源,要不Vue会报跨域错误

image.png

from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["http://localhost", "http://localhost:3010"]  # 允许的跨域来源
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,  # 允许跨域的源
    allow_credentials=True,  # 是否允许携带cookie
    allow_methods=["*"],  # 允许的方法,这里设置为所有方法
    allow_headers=["*"],  # 允许的请求头,这里设置为所有请求头
)
@app.post("/upload-image/")
async def upload_image(file: UploadFile):
    # 检查文件是否为图片
    if not file.content_type.startswith("image/"):
        return {"message": "The uploaded file is not an image."}

    # 保存图片到本地
    # with open("received_image.jpg", "wb") as buffer:
    #     await file.seek(0)
    #     await file.readinto(buffer)

    return {"message": "Image successfully uploaded!"}