0

我正在尝试提供 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....')
4

2 回答 2

1

您看到的错误是告诉您 Content-Type 不是字符串。Content-Type 是一个 HTTP 标头。据我所知,HTTP 标头必须是字符串。

我相信您想要作为响应正文传递的 base64 编码文件。FileResponse 在这里不合适,因为您可能希望将编码字符串作为正文传递,而 FileResponse 需要一个路径,然后它会读取并设置正文。

于 2013-09-16T13:22:18.277 回答
1

FileResponse专门用于上传文件作为响应(因此是路径参数)。在您的情况下,您希望在上传文件之前对其进行 base64 编码。这意味着没有FileResponse

由于您已将文件读入内存,您只需将内容上传到Response.

response = Response(encoded_string,
                    request=request,
                    content_type=sContentType+';base64')

我实际上不确定与类型content_encoding的比较如何;base64,但我认为编码更常用于压缩内容。YMMV。

于 2013-09-16T17:33:30.617 回答