I'm trying to serve base64 encoded image files and failing. Either I get UTF-8 encoded responses or the line return response
errors in an interesting way. Mostly everything I've tried can be seen as commented out code in the excerpt below. Details of the traceback follow that.
My question is: How can I return base64 encoded files?
#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
Uncommenting the line #content_encoding = encoded_string
gives me the error:
AssertionError: Header value b'/9j/4AAQSkZJRgABAQAA' is not a string in ('Content-Encoding', b'/9j/4AAQSkZJRgABAQAA....')
FileResponse
is used specifically for uploading a file as a response (hence the path argument). In you're case you want to base64-encode the file before uploading it. This means no FileResponse
.
Since you've read the file into memory you can just upload the content in a Response
.
response = Response(encoded_string,
request=request,
content_type=sContentType+';base64')
I'm not actually sure how content_encoding
compares to the ;base64
on the type, but I think the encoding is used more commonly for gzipped content. YMMV.