user984003 user984003 - 2 months ago 33
Python Question

Upload text file to Google Cloud Storage with Python api-client-library. Works with image, not text

I'm trying to upload a text file from my non-Google server to Google storage. It works when the file is an image (png), but not when it's a text file. I get

<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()

Answer

The key was to include mimetype:

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

Others:

mimetype='image/png

mimetype='application/gzip