如何使用Django发布和检索blob

jdgnovmf  于 2023-08-08  发布在  Go
关注(0)|答案(2)|浏览(124)

我有一个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"])

fkaflof6

fkaflof61#

blob是二进制数据,所以你可以在Django的request.body中找到它。它的Bytes编码(不是Unicode)。
主体原始HTTP请求主体,作为字节串。这对于以与传统HTML表单不同的方式处理数据非常有用:二进制图像、XML有效负载等。

46scxncf

46scxncf2#

很简单,你可以...读一读:

#views.py
from django.views import View

class Upload(View):

    def get(self, request):     
        # Sanity check if your server is up and running, reply to GET HTTP requests
        print('Got get request...') # log it for the debug purpose
        return HttpResponse('<H1>It is GET request, use POST</H1>', status=200)        

    def post(self, request):
        # Here, I'm using it with plupload.js for the chunked upload, but it would work anyway
        ... ## here, you'd do something with the headers
        file_name = request.POST['name'] # or some constant 'file_name_with_path.bin'
        chunk_num = int(request.POST['chunk']) # get it from the request 
        
        ## Finally, you know this is multipart-type, and headers are okay, let store it! 
        uploaded_file = request.FILES['file'] # data from the request
        if chunk_num == 0: 
            ## The very first chunk — create/overwrite a 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 to 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)


Nota贝内:我知道,这个问题有点老了,但我有同样的问题,并在没有时间解决它,但我挣扎着试图通过搜索最初找到一个解决方案.

相关问题