簡體   English   中英

如何從 FastAPI 中的 UploadFile 獲取文件路徑?

[英]How to get file path from UploadFile in FastAPI?

基本上,我正在嘗試創建一個端點以將文件上傳到 S3

async def upload_files(filepath: str, upload_file_list: List[UploadFile] = File(...)):
    for upload_file in upload_file_list:
        abs_file_path = "/manual/path/works" + upload_file.path
        # Replace above line to get absolute file path from UploadFile
        response = s3_client.upload_file(abs_file_path,bucket_name,
                                                   os.path.join(dest_path, upload_file.filename))

以上是我將多個文件上傳到 S3 存儲桶的代碼。 s3_client.upload_file()接受要上傳的文件的絕對文件路徑。 當我手動放置完整路徑時它正在工作。

這沒有用:

response = s3_client.upload_file(upload_file.filename, bucket_name,
                                                   os.path.join(dest_path, upload_file.filename))

有沒有辦法在FastAPI中獲得這個絕對路徑? 或者在不復制或寫入文件的情況下使用temp_path的任何替代方法?

如果沒有,那么FastAPI的任何替代方法都可以使用boto3將文件上傳到 S3

UploadFile 使用 Python 的SpooledTemporaryFile ,它是“存儲在內存中的文件”,“一關閉就銷毀”。 您可以讀取文件內容(ie, contents = await file.read()) ,然后將這些字節上傳到您的服務器(如果允許),或者請查看這個關於如何復制上傳內容的答案文件放入NamedTemporaryFile ,與 SpooledTemporaryFile 不同,“保證在文件系統中具有可見的名稱”,“可用於打開文件”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM