[英]How to get file path from UploadFile in FastAPI?
Basically, I'm trying to create an endpoint to Upload files to S3基本上,我正在尝试创建一个端点以将文件上传到 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))
Above is my code to upload multiple files to the S3 bucket.以上是我将多个文件上传到 S3 存储桶的代码。
s3_client.upload_file()
accepts an absolute file path of the file to upload. s3_client.upload_file()
接受要上传的文件的绝对文件路径。 It's working when I manually put the full path.当我手动放置完整路径时它正在工作。
This didn't work:这没有用:
response = s3_client.upload_file(upload_file.filename, bucket_name,
os.path.join(dest_path, upload_file.filename))
Is there a way to get this absolute path in FastAPI
?有没有办法在
FastAPI
中获得这个绝对路径? Or any alternative with temp_path
without copying or writing the file?或者在不复制或写入文件的情况下使用
temp_path
的任何替代方法?
If not, then any alternative with boto3
to upload files to S3 using FastAPI
如果没有,那么
FastAPI
的任何替代方法都可以使用boto3
将文件上传到 S3
UploadFile uses Python's SpooledTemporaryFile , which is a "file stored in memory", and "is destroyed as soon as it is closed". UploadFile 使用 Python 的SpooledTemporaryFile ,它是“存储在内存中的文件”,“一关闭就销毁”。 You can either read the file contents
(ie, contents = await file.read())
and then upload these bytes to your server (if it permits), or please take a look at this answer on how to copy the contents of the uploaded file into a NamedTemporaryFile , which, unlike SpooledTemporaryFile, " is guaranteed to have a visible name in the file system" that "can be used to open the file".您可以读取文件内容
(ie, contents = await file.read())
,然后将这些字节上传到您的服务器(如果允许),或者请查看这个关于如何复制上传内容的答案文件放入NamedTemporaryFile ,与 SpooledTemporaryFile 不同,“保证在文件系统中具有可见的名称”,“可用于打开文件”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.