【发布时间】:2022-08-20 19:24:36
【问题描述】:
我的服务器上的文件应该如何上传到谷歌云存储?
我尝试过的代码如下所示,但是,它会引发类型错误,说预期的类型不是字节:
the expected type is not byte for:
blob.upload_from_file(file.file.read()).
虽然 upload_from_file 需要二进制类型。
@app.post(\"/file/\")
async def create_upload_file(files: List[UploadFile] = File(...)):
storage_client = storage.Client.from_service_account_json(path.json)
bucket_name = \'data\'
try:
bucket = storage_client.create_bucket(bucket_name)
except Exception:
bucket = storage_client.get_bucket(bucket_name)
for file in files:
destination_file_name = f\'{file.filename}\'
new_data = models.Data(
path=destination_file_name
)
try:
blob = bucket.blob(destination_file_name)
blob.upload_from_file(file.file.read())
except Exception:
raise HTTPException(
status_code=500,
detail=\"File upload failed\"
)
-
利用blob.upload_from_filename(file.filename)
-
@JohnHanley 谢谢,但是当我这样做时,它说找不到给定的文件名,可能是什么原因?
-
文件名是什么?它存在吗?
-
它取自 fastapi UploadFile: file = File(...)。 file.filename 存在。但是当传递给 blob.upload_from_filename(file.filename) 时,它会抛出“没有这样的文件或目录”的错误。
标签: python google-cloud-platform google-cloud-storage fastapi