fastapi实现文件上传,解决编码问题

本文共有849个字,关键词:

问题:使用fastapi框架时,如何进行文件上传?

方法:

方法一

import shutil
from fastapi import FastAPI, File, UploadFile  

app = FastAPI()

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    # 这里可以添加保存文件的逻辑
    # 例如,使用 Python 的内置 open() 函数将文件保存到服务器
    # 注意:出于安全考虑,您应该验证文件类型和大小
    with open(file.filename, "wb") as buffer:  
        shutil.copyfileobj(file.file, buffer)  

    return {"filename": file.filename}

方法二

@app.post("/uploadfile2/")
async def create_upload_file(file: UploadFile = File(...)):
    with open(file.filename, "w") as fin:  
        fin.write(file.file.read().decode('utf8'))  

    return {"filename": file.filename}

方法二如果上传的文件不是utf-8格式就会报错,无法保存,所以推荐方法一

版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。
添加新评论
暂无评论