问题
I'm trying to get Django's HttpResponse to return binary data without much success. I've been trying different methods for a while now, but without success.
Encoding the string to ASCII works as long as the binary data values aren't outside the ASCII char scope, which is smaller than 0-255. The same happened when encoding with latin-1.
Creating byte string works nicely, but seems to fail if certain values are included, for example, if I have the following bytes included in the data: "\xf6\x52", I will get different bytes as a result. For some reason, the first byte, \xf6, gets converted to 0xfffd when I'm trying to review the result response.
I'd love to get some feedback and help with this.
Many thanks!
-A-
回答1:
return HttpResponse(data, content_type='application/octet-stream')
worked for me.
回答2:
Just cast your data a string.
return HttpResponse(str(data), 'image/jpeg')
来源:https://stackoverflow.com/questions/22276518/returning-binary-data-with-django-httpresponse