为什么图像属性没有方法文件名上传到 gcs?

问题描述

我正在尝试使用 python flask 将图像上传到 gcs。我已经参考了 google 提供的文档,https://cloud.google.com/appengine/docs/flexible/python/using-cloud-storage,但出现错误:-

AttributeError: 'str' 对象没有属性 'filename'

我严格按照文档中的文档进行操作,但仍然出现这些错误,我不知道为什么。

我的 html 表单:-

<form action="/register",method="POST",enctype="multipart/form-data">
 <input type="file",name="image",placeholder="Image">
</form>

我的 python 烧瓶代码:-

#fetch user image
    userImage = request.files["image"]
    #upload userImage
    #create storageclient
    gcs = storage.Client.from_service_account_json("projectalpha24-e0c2991ff2c0.json")
    #get storage bucket
    bucket = gcs.get_bucket("projectalpha24.appspot.com")
    #create a blob and upload file content
    blob = bucket.blob(userImage.filename)

    blob.upload_from_string(
        userImage.read(),content_type=userImage.content_type
    )

我不确定发生了什么。任何帮助将不胜感激。

编辑:我已经编辑了代码。我已将从表单中获取图像的方式更改为 request.files["image"] 并再次遵循上述文档 1 次。现在我收到一个错误:-

请求的 mimetype 是“application/x-www-form-urlencoded”而不是“multipart/form-data”,这意味着没有传输文件内容。要修复此错误,您应该在表单中提供 enctype="multipart/form-data"

虽然,正如你从我的表单代码中看到的,我确实在我的表单中包含了 enctype,但是,它给出了这个错误

解决方法

您需要通过 userImage = request.files.get("image") 获取文件对象。有关详细信息,请参阅 boolean indexing