我无法使用 Python 将名称中包含空格的文件上传到 Google Cloud Storage。我究竟做错了什么?

jol*_*rum 4 python flask google-cloud-storage

我是 Python 和 Google Cloud 的新手。我使用 Flask 创建了一个网页,用户可以在其中从他们的计算机中选择一个文件并将其上传到我已经创建的 GCS 存储桶。我正在关注使用 Google Python API 库的Google 文档示例。我可以上传名称仅为单个单词的文件,例如“image”,但如果我的文件名为“image one”,则会出现以下错误- FileNotFoundError:[Errno 2]没有这样的文件或目录:“image”一个.jpg'

这是我的代码:

@app.route('/upload', methods = ['GET'  , 'POST'])
def upload():
    if request.method == "POST":
        f = request.files['file']
        f.save(secure_filename(f.filename))
        gcs_upload(f.filename)

def gcs_upload(filename):
    storage_client = storage.Client()   # instantiate a client
    bucket = storage_client.bucket('bucket_name')
    blob=bucket.blob(filename)      # file name at the destination should be the same
    blob.upload_from_filename(filename)     # file to be uploaded

if __name__ == '__main__':
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    app.run(port=8080, debug=True)
Run Code Online (Sandbox Code Playgroud)

如果我正在编写生产级应用程序,那么我希望用户上传文件,即使文件名称中包含空格。

小智 5

我在自己的项目中重现了这个问题,您遇到的问题是由于使用secure_filename函数而引起的。根据werkzeug 文档,函数 secure_filename 将用下划线替换用户提供的文件名中的任何空格。添加一些日志记录您可能会看到:

f.filename # 'foo bar.png'
secure_filename(f.filename) # 'foo_bar.png'
Run Code Online (Sandbox Code Playgroud)

因此,当您调用gcs_upload函数时,您将传递原始文件名而不是 secure_filename 返回的文件名,并且错误消息指出此类文件不存在。

要解决此问题,只需将上传功能更改为:

def upload():
    if request.method == "POST":
        f = request.files['file']
        filename = secure_filename(f.filename)
        f.save(filename)
        gcs_upload(filename)
Run Code Online (Sandbox Code Playgroud)