How to post and retrieve blob with Django

人盡茶涼 提交于 2019-12-06 03:12:49

问题


I have a blob. It's an image that I resized using a <canvas>. I've verified that the data is correct by converting it to a url to test it as per the MDN guide. So far so good. Now, I'd like to post it to my Django server (along with some other inputs).

So I do this:

var fd = new FormData(form);
canvas.toBlob( function(blob) {
  fd.set("image0", blob, "image0.jpg");
}, "image/jpeg", 0.7);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/ajax-upload/', true);
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.send(fd);

I inspect the POST message with the network inspector console. My blob is confirmed as sent with the POST request and I can see the binary data send as the "image0" field.

-----------------------------1773139883502878911993383390
Content-Disposition: form-data; name="image0"; filename="blob"
Content-Type: image/png

So I handle the POST request with this view, accessible at url /ajax-upload/:

def ajax_upload(request):
    if request.method == 'POST':
        print(request.POST.urlencode())

This gives me nothing. Once I find out where my blob went, how can I turn it into an Image? Something like img = Image.open(request.POST["image0"])?


回答1:


A blob is binary data, so you can find it in the request.body in Django. Its Bytes encoded (not Unicode).

HttpRequest.body The raw HTTP request body as a byte string. This is useful for processing data in different ways than conventional HTML forms: binary images, XML payload etc.



来源:https://stackoverflow.com/questions/35805257/how-to-post-and-retrieve-blob-with-django

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!