如何将文件从本地磁盘上传到Google云存储桶?

时间:2018-11-09 11:56:53

标签: python-2.7 google-app-engine google-cloud-storage

我正在尝试将Excel和pdf文件从本地磁盘上传到Google云存储。 Excel使用python中的pandas库创建。当我尝试上传生成的文件时,出现此错误

'ascii' codec can't decode byte 0xd0 in position 217: ordinal not in range(128) 

我正在使用灵活的Appengine。这是上传文件的代码

def upload_to_gcs(file_path,file_name,file_type,bucket_name):
try:
    import google.cloud.storage
    storage_client = google.cloud.storage.Client.from_service_account_json(
        os.getcwd()+'relative_path_of_service_json_file')
    bucket = storage_client.get_bucket('bucket_name')
    d = bucket.blob(bucket_name+'/'+file_name+'.'+file_type)
    d.upload_from_filename(file_path)
except Exception, e:
        print str(e)

预先感谢

1 个答案:

答案 0 :(得分:0)

错误是因为存在无法将其转换为ASCII的字符。通常,由于文件名中的特殊字符或文件的编码方式,会出现这种错误。检查文件或文件名中是否存在任何ASCII可能有问题的字符。

这里还有另一个StackOverflow question关于相同的错误。在这个问题中,OP使用的是gsutil命令,但是最后,Python客户端库和该命令都做同样的事情,调用Cloud Storage API,因此两者的解决方案可以相同。 / p>

针对类似错误的其他解决方案以编程方式解决了问题。 Using decode("utf-8")decode(encoding='unicode-escape')。此解决方案也可以为您提供帮助,您应该尝试一下。

如果仍然找不到问题的根本原因,请直接尝试uploading the file through the API。这样,您无需使用Python客户端库即可检查问题是否仍然存在。