美文网首页
Fastapi上传下载文件

Fastapi上传下载文件

作者: AsdilFibrizo | 来源:发表于2021-09-02 09:13 被阅读0次

    1.上传文件 upload.py

    from typing import List
    from fastapi import FastAPI, File, UploadFile
    from fastapi.responses import HTMLResponse
    upload = FastAPI()
    
    # 第一种读取文件方法,读取二进制文件
    @upload.post("/files/")
    async def create_files(files: List[bytes] = File(...)):
        # 保存文件名
        # with open('保存文件名字', 'wb') as f:
        #     f.write(files[0])
        return {"file_sizes": [len(file) for file in files]}
    
    # 第二种读取文件的方法,会报错文件名,文件本身等信息
    @upload.post("/uploadfiles/")
    async def create_upload_files(files: List[UploadFile] = File(...)):
        
        # 保存文件
        # data = await files[0].read()
        # with open('保存文件名字', 'wb') as f:
        #     f.write(data)
        return {"filenames": [file.filename for file in files]}
    
    @upload.get("/")
    async def main():
        content = """
    <body>
    <form action="/files/" enctype="multipart/form-data" method="post">
    <input name="files" type="file" multiple>
    <input type="submit">
    </form>
    <form action="/uploadfiles/" enctype="multipart/form-data" method="post">
    <input name="files" type="file" multiple>
    <input type="submit">
    </form>
    </body>
        """
        return HTMLResponse(content=content)
    
    if __name__ == '__main__':
        import uvicorn
        uvicorn.run('upload:upload', host='0.0.0.0', port=8900)
    

    输入:http://0.0.0.0:8900/


    上传文件

    2.下载文件 download.py

    import pandas as pd
    from fastapi import FastAPI
    from fastapi.responses import FileResponse,StreamingResponse,Response
    import io
    
    download = FastAPI()
    file_path = "文件路径"
    
    # 假设有个pandas DataFrame文件文件需要保存
    @download.get("/from_data/")
    def main():
        df = pd.DataFrame([1,2,3])
        stream = io.StringIO()
        df.to_csv(stream, index=False)
        response = StreamingResponse(iter([stream.getvalue()]), media_type="text/csv")
        response.headers["Content-Disposition"] = "attachment; filename=export.csv"
        return response
    
    # 假设我们预定了文件的路径
    @download.get("/from_path/")
    def main():
        return FileResponse(path=file_path, filename=file_path, media_type='py')
    
    
    if __name__ == '__main__':
        import uvicorn
        uvicorn.run('download:download', host='0.0.0.0', port=8800)
    

    输入:http://0.0.0.0:8900/from_data/ 或者 http://0.0.0.0:8900/from_path/

    下载文件

    3.下载excel文件

    # -*- coding: utf-8 -*-
    """
    -------------------------------------------------
       File Name:     xxx
       Description :
       Author :       asdil
       date:          2022/5/11
    -------------------------------------------------
       Change Activity:
                       2022/5/11:
    -------------------------------------------------
    """
    __author__ = 'Asdil'
    import pandas as pd
    from fastapi import FastAPI
    from fastapi.responses import FileResponse,StreamingResponse,Response
    import io
    
    download = FastAPI()
    file_path = "文件路径"
    
    # 假设有个pandas DataFrame文件文件需要保存
    @download.get("/from_data/")
    def main():
        df = pd.DataFrame([1,2,3])
        stream = io.BytesIO()
        writer = pd.ExcelWriter(stream, engine='xlsxwriter')
        df.to_excel(writer, index=False)
        writer.save()
        xlsx_data = stream.getvalue()
        response = StreamingResponse(io.BytesIO(xlsx_data))
        response.media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        response.headers['Content-Disposition'] = f'attachment; filename="这里是你要保存的名字.xlsx"'.encode("utf-8").decode("latin1")
        return response
    
    
    if __name__ == '__main__':
        import uvicorn
        uvicorn.run('xxx:download', host='0.0.0.0', port=8800)
    

    相关文章

      网友评论

          本文标题:Fastapi上传下载文件

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