使用Python api-client-library将文本文件上传到Google Cloud Storage。适用于图像,而不是文本

时间:2015-09-20 23:34:42

标签: python google-cloud-storage google-cloud-platform google-api-python-client

我正在尝试将非Google服务器上的文本文件上传到Google存储空间。当文件是图像(png)时它起作用,但是当它是文本文件时它不起作用。我得到了

<HttpError 400 when requesting https://www.googleapis.com/upload/storage/v1/b/my_bucket_name/o?uploadType=resumable&alt=json&predefinedAcl=publicRead&name=media%2Fmy_file.txt returned "Bad Request"

credentials = GoogleCredentials.get_application_default()
google_service = build('storage', 'v1', credentials=credentials)

bucket = "my_bucket_name"

filename = "/home/path/my_image.png"
filename_new = "media/my_image.png"

# Fails with txt file instead of image
#filename = "/home/path/my_file.txt"
#filename_new = "media/my_file.txt"

media = MediaFileUpload(filename, chunksize=4194304, resumable=True)
req = google_service.objects().insert(bucket=bucket,
        name=filename_new ,
        media_body=media,
        body={"cacheControl": "public,max-age=31536000"},
        predefinedAcl='publicRead')
resp = None
while resp is None:
    status, resp = req.next_chunk()

1 个答案:

答案 0 :(得分:1)

关键是要包含mimetype:

filename = "/home/path/my_file.txt"
media = MediaFileUpload(filename, chunksize=4194304,  mimetype='plain/text', resumable=True)

其他:

mime类型='图像/ PNG

mime类型='应用/ gzip的