简体   繁体   English

使用Python api-client-library将文本文件上传到Google Cloud Storage。 适用于图片,而非文字

[英]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. 我正在尝试将文本文件从非Google服务器上载到Google存储。 It works when the file is an image (png), but not when it's a text file. 当文件是图像(png)时有效,但是当它是文本文件时无效。 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()

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试使用适用于python的Google API客户端将UTF-8文本文件上传到Google云端硬盘时,我收到了UnicodeDecodeError - When attempting to upload a UTF-8 text file to Google Drive with the Google API client for python, I get a UnicodeDecodeError GCS - 从 Google Cloud Storage 直接读取文本文件到 python - GCS - Read a text file from Google Cloud Storage directly into python 将文件上传到Appengine上的Google Cloud Storage(Python) - File Upload To Google Cloud Storage on Appengine(Python) 如何将文件上传到 Python 3 上的 Google Cloud Storage? - How to upload a file to Google Cloud Storage on Python 3? 使用于访问谷歌云存储的谷歌python客户端库达到了一个存根API - Make the Google python client library for accessing Google cloud storage hit a stubbed API 在开发服务器上使用Google Cloud Storage客户端库显示图像 - Displaying an image with Google Cloud Storage client library on dev server 通过pip安装Google Cloud Storage客户端库-Python GAE - Install Google Cloud Storage Client Library with pip — Python GAE 如何使用 Python 客户端库修改 Google Cloud Storage object? - How to modify a Google Cloud Storage object using Python client library? 如何从Python脚本上传Google Cloud Storage上的字节图像 - How to upload a bytes image on Google Cloud Storage from a Python script 如何使用 Python API 在 Google Cloud Storage 上上传文件夹 - How to upload folder on Google Cloud Storage using Python API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM