【问题标题】:How to save JPG/PNG files and have it retain correct Content-Type如何保存 JPG/PNG 文件并让它保留正确的 Content-Type
【发布时间】:2013-02-21 19:25:36
【问题描述】:

我正在通过以下方式将来自服务器的图片文件保存在 S3 中的存储桶中:

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 时显示。

有什么办法可以缓解这种情况?

【问题讨论】:

  • 我不熟悉这个你使用的库,但是当你上传文件到s3时,你需要在api调用中传递content-type header。

标签: amazon-web-services amazon-s3 boto django-storage


【解决方案1】:

当你这样做时

jpg_data = response.read()

我相信 boto 会丢失有关文件扩展名的信息,它用于猜测 mimetype。所以当你存储它的时候

my_file.write(jpg_data)

所有 boto/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)

您可以通过使用标头参数指定 Content-Type 来控制它

如果您想保留原始获取的 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)

【讨论】:

    猜你喜欢
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    相关资源
    最近更新 更多