user984003 user984003 - 10 months ago 88
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 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 ,
body={"cacheControl": "public,max-age=31536000"},
resp = None
while resp is None:
status, resp = req.next_chunk()

Answer Source

The key was to include mimetype:

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