如何使用Django发布和检索blob [英] How to post and retrieve blob with Django
问题描述
我有一个 blob
。这是一个使用< canvas>
调整大小的图像。我已经通过将数据转换为网址来验证数据是否正确,以便根据 MDN指南。到现在为止还挺好。现在,我想把它发布到我的Django服务器(以及一些其他的输入)。
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).
所以我这样做:
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);
我使用网络检查器控制台检查POST消息。我的blob被确认为与POST请求一起发送,我可以看到发送的二进制数据为image0字段。
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
所以我处理POST请求与此视图,可访问url / ajax-upload /
:
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())
这给我什么。一旦我找到我的blob去哪里,我该怎么把它变成一个图像
?像 img = Image.open(request.POST [image0])
?
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"])
?
推荐答案
一个blob是二进制数据,所以你可以在Django的 request.body
中找到它。它的字节
编码(而不是Unicode)。
A blob is binary data, so you can find it in the request.body
in Django. Its Bytes
encoded (not Unicode).
HttpRequest.body
原始HTTP请求体作为字节串。这对于处理数据的方式不同于传统的HTML格式:二进制图像,XML有效载荷等。
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.
这篇关于如何使用Django发布和检索blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!