• 基于FastAPI的文件上传和下载


    基于FastAPI的文件上传和下载

    一、前言

    为了实现ASR的可视化界面,在各个博客中寻觅了一波找找文件上传和下载的例子,没有找到能完整实现这个功能的,有也只是有一部分(菜菜求捞捞),看了甚是烦恼,后来找gpt大爷来回交互了几下,把功能实现了。记录一下过程。

    二、实现步骤

    对了,能来查这个问题的兄弟,默认你对fastapi有了解了hh,就不多介绍了,单刀直入主题,怎么实现功能。

    1、环境配置

    这个功能实现涉及到三个库: fastapi、uvicorn、 requests。

    pip install fastapi uvicorn requests -i
    https://pypi.tuna.tsinghua.edu.cn/simple

    2、服务端代码

    文件名:upload.py

    import os.path
    
    import uvicorn
    
    from fastapi import FastAPI, File, UploadFile
    from fastapi.responses import FileResponse
    
    app = FastAPI()
    
    @app.get("/")
    async def hello():
    
        return {"ret": 'hello'}
    
    @app.post("/uploadfile/")
    async def create_upload_file(file: UploadFile = File(...)):
        print(file)
        if not os.path.exists('uploaded_files'):
            os.mkdir('uploaded_files')
        with open(f"uploaded_files/{file.filename}", "wb") as f:
            f.write(await file.read())
        return {"filename": file.filename}
    
    @app.get("/downloadfile/{filename}")
    async def download_file(filename: str):
        file_path = f"uploaded_files/{filename}"
        return FileResponse(file_path, media_type="application/octet-stream", filename=filename)
    
    
    if __name__ == '__main__':
        uvicorn.run('upload:app', host='127.0.0.1', port=18005, reload=True)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    运行结果参考:
    在这里插入图片描述

    3、客户端代码

    import os
    
    import requests
    def upfile(file_path):
        url = "http://127.0.0.1:18005/uploadfile/"
    
        try:
            with open(file_path, "rb") as f:
                files = {"file": (file_path, f)}
                response = requests.post(url, files=files)
    
            if response.status_code == 200:
                print(response.json())
                return True
            else:
                print(f"Request failed with status code {response.status_code}")
                return False
        except Exception as e:
            print(e)
            return False
    def download(fileName):
        url = "http://127.0.0.1:18005/downloadfile/{}".format(fileName)
        try:
            res=requests.get(url)
            if res.status_code==200:
                with open(fileName,'wb') as w:
                    w.write(res.content)
    
                return True
            else:
    
                return False
        except Exception as e:
            print(e)
            return False
    def main():
        file_path = r"C:\Users\Admin\Pictures\LesNo2Text.png"
    
        upfile(file_path)
        fileName=os.path.basename(file_path)
        print('待下载的文件名字:'.format(fileName))
        ret=download(fileName)
        if ret:
            print('下载成功:' + fileName)
        else:
            print('下载失败:'+fileName)
    if __name__=="__main__":
        main()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    运行结果参考:
    在这里插入图片描述到这里就结束了,有遇到什么bug欢迎在下面评论区提,相对其他博主我还是学生相对活跃一些hh。

  • 相关阅读:
    新年学新语言Go之四
    SpringBoot配置事务、统一异常处理以及日志记录【项目实现】
    C. Doremy‘s City Construction(思维)
    Unity URP 如何写基础的曲面细分着色器
    看板系统如何异地电脑手机访问?主机内网ip端口映射域名外网访问
    Linux编辑器-vim使用
    微信小程序 - - - input和键盘一起上弹如何实现?
    【漏洞复现】WebLogic XMLDecoder反序列化(CVE-2017-10271)
    Python【多分支实际应用的练习】
    【10套模拟】【2】
  • 原文地址:https://blog.csdn.net/qq_51116518/article/details/133614101