美文网首页
FastApi(8)-文件处理

FastApi(8)-文件处理

作者: 呦丶耍脾气 | 来源:发表于2025-03-18 17:00 被阅读0次

1.上传文件

1.1 代码清单

import os
from fastapi import APIRouter, Form, UploadFile
from app.types import response
...

@router.post("/upload/file")
async def uploadFile(file: UploadFile | None = None, file_type: str = Form()) -> response.HttpResponse:
    """ 文件上传"""
    if not file:
        return response.ResponseFail("文件信息不能为空~")

    try:
        # 构造保存目录 根目录下/tmp/{fileType}
        save_path = os.path.join(os.getcwd(), "tmp", file_type)
        # 不存在则创建目录
        os.makedirs(save_path, exist_ok=True)
        # 拼接文件全路径
        file_path = os.path.join(save_path, file.filename)
        # 读取文件内容并写入目标文件
        contents = await file.read()
        with open(file_path, "wb") as f:
            f.write(contents)
        body = {
            "fileName": file.filename,
            "fileType": file_type,
            "size": file.size,
        }
        return response.ResponseSuccess(body)
    except Exception as e:
        return response.ResponseFail("文件上传失败:" + str(e))

2.2 请求验证

2.3 保存结果

3.访问文件

在某些场景下,我们需要提供一个地址,可以让前端工程师或者第三方来访问静态资源,比如返回一张图片或者一个文件。在FastAPI中,静态资源的访问实现(只有挂在才可以直接访问),叫:挂载

3.1 静态目录

...
├── app
├── main.py
...
├── static
│   ├── img
│   │   └── test.jpg
│   └── root.txt
...

3.2 挂载

在服务启动入口,加上下面server.mount(...)这行代码,即可进行静态资源进行访问。

...
# 实例化
server = FastAPI(redoc_url=None, docs_url="/apidoc", title="FastAPI学习")
# 挂载静态资源目录
server.mount("/static", StaticFiles(directory="static"), name="static")
...

3.3 访问

比如下面访问静态资源图片: static/img/test.jpg

4.下载文件

在工作中下载文件的场景,大部分都是异步导出文件,如发个异步任务,查出数据并把结果上传到oss,然后在下载列表中查看状态并下载结果。但是也有些特殊场景,需要直接在浏览器中,实现下载文件,下面是实现效果:

4.1 代码清单

文件: app/router/param_router.py

from fastapi.responses import FileResponse # 导入包
...

@router.get("/file/download")
async def downloadFile() -> FileResponse:
    """下载文件"""
    file_name = "yapi.png"
    file_path = os.path.join(os.getcwd(), "static/img", file_name)
    return FileResponse(file_path, filename=file_name)

4.2 请求验证

相关文章

网友评论

      本文标题:FastApi(8)-文件处理

      本文链接:https://www.haomeiwen.com/subject/tmogmjtx.html