使用 Python api-client-library 将文本文件上传到 Google 云存储。适用于图像,而不是文本
Upload text file to Google Cloud Storage with Python api-client-library. Works with image, not text
我正在尝试将文本文件从我的非 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()
关键是要包含 mimetype:
filename = "/home/path/my_file.txt"
media = MediaFileUpload(filename, chunksize=4194304, mimetype='plain/text', resumable=True)
其他:
mimetype='image/png'
mimetype='application/gzip'
我正在尝试将文本文件从我的非 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()
关键是要包含 mimetype:
filename = "/home/path/my_file.txt"
media = MediaFileUpload(filename, chunksize=4194304, mimetype='plain/text', resumable=True)
其他:
mimetype='image/png'
mimetype='application/gzip'