我有一台blob。这是一张我用<canvas>调整大小的图片。我已经通过将数据转换为url并按照the MDN guide对其进行测试来验证数据的正确性。到目前一切尚好。现在,我想将其发布到我的Django服务器(以及其他一些输入)。
所以我这样做:
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“字段发送的二进制数据。
-----------------------------1773139883502878911993383390
Content-Disposition: form-data; name="image0"; filename="blob"
Content-Type: image/png所以我用这个视图来处理POST请求,这个视图可以在url /ajax-upload/上访问
def ajax_upload(request):
if request.method == 'POST':
print(request.POST.urlencode())这没有给我任何帮助。一旦我发现我的blob到哪里去了,我怎么把它变成一个Image呢?像img = Image.open(request.POST["image0"])这样的东西
发布于 2016-06-06 01:30:35
blob是二进制数据,因此您可以在Django的request.body中找到它。它的Bytes编码(不是Unicode)。
HttpRequest.body原始的HTTP请求正文为一个字节字符串。这对于以不同于传统HTML表单的方式处理数据非常有用:二进制图像、XML有效载荷等。
发布于 2021-06-11 00:12:14
这很简单,你可以...请阅读以下内容:
#views.py
class Upload(View):
def get(self, request):
# Sanity check if your server is up and running, reply to HTTP request
print('Got get request...') # log it for debug purpose
return HttpResponse('<H1>POST endpoint.</H1>', status=200)
def post(self, request):
## here I used it with plupload.js for chunked upload, but it works anyway
... ## here you do something with headers
file_name = request.POST['name'] # or some 'file_name_with_path.bin'
chunk_num = int(request.POST['chunk']) # get it from the request
## Finally, you know this is multipart and headers are okay, let save it.
uploaded_file = request.FILES['file'] # data from request
if chunk_num == 0:
## The very first chunk — create/overwrite binary file
with open(file_name, 'wb+') as f:
f.write(uploaded_file.read()) # so, just read it from the request
else:
## Next chunks — append the file!
with open(file_name, 'ab') as f:
f.write(uploaded_file.read())在您的案例中:
def ajax_upload(request):
...
img = Image.open(request.POST["file"].read())
...
return HttpResponse('{"Status":"OK"}', status=200)PS:我知道,这个问题有点老了,但我也有同样的问题,很快就解决了,但我最初很难通过搜索找到解决方案。
https://stackoverflow.com/questions/35805257
复制相似问题