【发布时间】:2013-09-17 01:33:30
【问题描述】:
我正在尝试提供 base64 编码的图像文件,但失败了。要么我得到 UTF-8 编码的响应,要么以一种有趣的方式得到 return response 行错误。大多数我尝试过的所有东西都可以看作是下面摘录中的注释代码。回溯的详细信息如下。
我的问题是:如何返回 base64 编码文件?
#import base64
#with open(sPath, "rb") as image_file:
#encoded_string = base64.b64encode(image_file.read())
dContentTypes = {
'bmp' : 'image/bmp',
'cod' : 'image/cis-cod',
'git' : 'image/gif',
'ief' : 'image/ief',
'jpe' : 'image/jpeg',
.....
}
sContentType = dContentTypes[sExt]
response = FileResponse(
sPath,
request=request,
content_type= sContentType#+';base64',
#content_encoding = 'base_64'
#content_encoding = encoded_string
)
return response
取消注释 #content_encoding = encoded_string 行会给我错误:
AssertionError: Header value b'/9j/4AAQSkZJRgABAQAA' is not a string in ('Content-Encoding', b'/9j/4AAQSkZJRgABAQAA....')
【问题讨论】:
-
为什么不直接提供图片?只有在 CSS 或 HTML 中直接嵌入时才需要 Base64 编码资源。提供 HTTP 响应时,您只需提供未编码的资源。
-
@MartijnPieters:这是野兽的本性......我有一个脚本可以抓取图像并将它们存储在一个不错的地方,我有一个需要显示它们的页面。不幸的是,由于我无权访问配置,我无法以正常方式为他们提供服务。此外,由于应用程序的性质,我需要能够动态获取其中一些(我可以将它们隐藏在页面上的某个位置并根据需要取消隐藏它们,但它们有很多)