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

在使用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!"}
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
el-upload标签是element-ui组件库的一个上传组件,可以方便地实现图片上传功能。调用上传图片接口实现图片上传的具体步骤如下: 1. 在Vue组件中引入el-upload组件: ``` <template> <el-upload class="upload-demo" action="/api/upload" :on-success="handleSuccess" :on-error="handleError" :before-upload="beforeUpload" > <el-button size="small" type="primary">点击上传</el-button> </el-upload> </template> ``` 2. 在data中定义上传文件的参数: ``` data() { return { imageUrl: '', uploadHeaders: { 'Authorization': 'Bearer ' + getToken(), }, }; }, ``` 这里需要注意的是,上传图片时需要带上token进行身份验证,因此我们在uploadHeaders中添加了Authorization参数,值为当前用户的token。 3. 定义上传成功和上传失败的回调函数: ``` methods: { handleSuccess(response, file, fileList) { this.imageUrl = response.url; this.$message({ message: '上传成功', type: 'success', }); }, handleError() { this.$message.error('上传失败'); }, }, ``` 上传成功后,我们可以在handleSuccess回调函数中获取到服务器返回的图片url,然后将其赋值给imageUrl,以便在页面上显示上传的图片。 4. 定义上传前的钩子函数: ``` beforeUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!'); return false; } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); return false; } return true; }, ``` 在beforeUpload函数中,我们可以对上传的图片进行一些校验,比如限制图片的格式和大小等。 5. 最后,在服务器端编上传图片接口,接收图片文件并保存到服务器中。 以上就是使用el-upload标签调用上传图片接口实现图片上传的具体步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值