Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve an image in Django using jquery

I am trying to update a div element in my html page with a png image which gets returned from the Django server.

In my client-side script where I send an ajax POST request on a button click, I have -

    $('#mybtn').click(function (event) {
        event.preventDefault();
        $.ajax({
            url: "/analysis",
            type: "POST",
            data: { 'data': $("#analysis_list").val(), csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value },
            success: function (response) {
                $('#imagediv').html('<img src=' + response + ' />');
            },
        });
    });

In my views.py, I have -

def analysis(request):
    dataFromClient = dict(request.POST)['data'][0]
    pathToImg = testAnalytics(dataFromClient)
    img = Image.open(pathToImg)
    response = HttpResponse(content_type="image/png")
    img.save(response, "PNG")
    return response

Where testAnalytics method generates the image to be displayed according to the data sent by client and returns the path to it. Image is imported from PIL.

I am facing problem with rendering the image at client-side javascript. When I assign response to src attribute of the <img> tag, I see raw image data on the browser instead of the image (as discussed in here - How to update a div with an image in Django?). I am not sure where I am going wrong.

I have also tried base64 encoding on the response as follows (but not sure whether I have implemented correctly) -

success: function (response) {
                $('#imagediv').html('<img alt="Embedded Image" src="data:image/png;base64,' + response + '" />');
            }

I have referred to following links to get upto this point -
Django: How to render image with a template
Serve a dynamically generated image with Django

I am fairly new to web-programming as well as Django. Any insights regarding the problem will be really helpful. Thanks in advance.

like image 458
Amogh Kulkarni Avatar asked Oct 20 '22 13:10

Amogh Kulkarni


1 Answers

Try encoding the image using base64 before you send it.

import base64
#rest of your code 
with open("pathToImage.png", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

Then

success: function(response){
            $('#imagediv').html('<img src="data:image/png;base64,' + response + '" />');
like image 79
statBeginner Avatar answered Nov 01 '22 13:11

statBeginner