1

我試圖將文件從我的非Google服務器上傳到Google存儲。它在文件是圖像(png)時起作用,但在文本文件時不起作用。我得到使用Python api-client-library將文本文件上傳到Google Cloud Storage。適用於圖片,而不是文字

<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

的關鍵是包括MIME類型:

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

其他:

mime類型= '圖像/ PNG

mime類型=' 應用/ gzip的

相關問題