javascript - How to serve an image in Django using jquery -
i trying update div
element in html page png image gets returned django server.
in client-side script send ajax post request on button click, 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 views.py, 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 image displayed according data sent client , returns path it. image
imported pil
.
i facing problem rendering image @ client-side javascript. when assign response
src
attribute of <img>
tag, see raw image data on browser instead of image (as discussed in here - how update div image in django?). not sure going wrong.
i have tried base64 encoding on response follows (but not sure whether have implemented correctly) -
success: function (response) { $('#imagediv').html('<img alt="embedded image" src="data:image/png;base64,' + response + '" />'); }
i have referred following links upto point -
django: how render image template
serve dynamically generated image django
i new web-programming django. insights regarding problem helpful. in advance.
try encoding image using base64 before send it.
import base64 #rest of code open("pathtoimage.png", "rb") image_file: encoded_string = base64.b64encode(image_file.read())
then
success: function(response){ $('#imagediv').html('<img src="data:image/png;base64,' + response + '" />');
Comments
Post a Comment