2013-02-21 76 views
0

我從一臺服務器保存圖片文件在S3水桶以下列方式正確的Content-Type:如何保存JPG/PNG文件,並把它保留

request = urllib2.Request('http://link.to/file.jpg') 
response = urllib2.urlopen(request) 
jpg_data = response.read() 

storage = S3BotoStorage(bucket='icanhazbukkit') 
my_file = storage.open(path_to_new_file, 'w') 
my_file.write(jpg_data) 
my_file.close() 

文件被寫入,但地方一路上MIME上下文丟失,並且保存的圖像將返回Content-Type: binary/octet-stream,瀏覽器將嘗試下載,而不是在URL的命中時顯示。

任何方式我可以緩解這一點?

+2

我不熟悉你使用的庫,但是當你上傳一個文件到s3時,你需要在api調用中傳遞內容類型的頭文件。 – datasage 2013-02-21 19:32:30

回答

3

當你

jpg_data = response.read() 

我相信博託損失大約文件擴展名,它用來猜測MIME類型的信息。所以你的時候它存儲與

my_file.write(jpg_data) 

所有博託/ S3知道的是,它具有某種二進制數據的寫入。

如果更換程序中的這些行:

storage = S3BotoStorage(bucket='icanhazbukkit') 
my_file = storage.open(path_to_new_file, 'w') 
my_file.write(jpg_data) 
my_file.close() 

bucket = conn.create_bucket('icanhazbukkit') 
k = Key(bucket) 
k.name = "yourfilename" 
header = {'Content-Type' : 'image/jpeg'} 
k.set_contents_from_string(jpg_data, header) 

您可以通過使用標頭PARAM指定它控制的Content-Type

如果你想保留內容類型從您的原始獲得,您可以這樣做:

request = urllib2.Request('http://link.to/file.jpg') 
response = urllib2.urlopen(request) 
file_data = response.read() 

bucket = conn.create_bucket('icanhazbukkit') 
k = Key(bucket) 
k.name = "yourfilename" 
origType = response.info().gettype() 
header = {'Content-Type' : origType} 
k.set_contents_from_string(file_data, header)