A flexible way to return binary data from Django is to first encode the data using Base64.
Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.
Since the Base64 encoded data is ASCII, the default HTTP response content type of text/html; charset=utf-8
works fine.
Image Example
Django
import base64
from io import BytesIO
from django.http import HttpRequest, HttpResponse
import PIL.Image
def image_test(request: HttpRequest) -> HttpResponse:
file_stream = BytesIO()
image_data = PIL.Image.open('/path/to/image.png')
image_data.save(file_stream)
file_stream.seek(0)
base64_data = base64.b64encode(file_stream.getvalue()).decode('utf-8')
return HttpResponse(base64_data)
Web Browser
After fetching the data
from Django, the base64 data can be used to create a data URL.
// `data` fetched from Django as Base64 string
const dataURL = `data:image/png;base64,${data}`;
const newImage = new Image();
newImage.src = dataURL;
$('#ImageContainer').html(newImage);
JSON Response
The Base64 data may also be returned as part of a JSON response:
import base64
from io import BytesIO
from django.http import HttpRequest, JsonResponse
import PIL.Image
def image_test(request: HttpRequest) -> JsonResponse:
file_stream = BytesIO()
image_data = PIL.Image.open('/path/to/image.png')
image_data.save(file_stream)
file_stream.seek(0)
base64_data = base64.b64encode(file_stream.getvalue()).decode('utf-8')
json_data = dict()
json_data['base64Data'] = base64_data
return JsonResponse(json_data)