问题
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