首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Django发布和检索blob

如何使用Django发布和检索blob
EN

Stack Overflow用户
提问于 2016-03-05 04:14:11
回答 2查看 4.8K关注 0票数 5

我有一台blob。这是一张我用<canvas>调整大小的图片。我已经通过将数据转换为url并按照the MDN guide对其进行测试来验证数据的正确性。到目前一切尚好。现在,我想将其发布到我的Django服务器(以及其他一些输入)。

所以我这样做:

代码语言:javascript
复制
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“字段发送的二进制数据。

代码语言:javascript
复制
-----------------------------1773139883502878911993383390
Content-Disposition: form-data; name="image0"; filename="blob"
Content-Type: image/png

所以我用这个视图来处理POST请求,这个视图可以在url /ajax-upload/上访问

代码语言:javascript
复制
def ajax_upload(request):
    if request.method == 'POST':
        print(request.POST.urlencode())

这没有给我任何帮助。一旦我发现我的blob到哪里去了,我怎么把它变成一个Image呢?像img = Image.open(request.POST["image0"])这样的东西

EN

回答 2

Stack Overflow用户

发布于 2016-06-06 01:30:35

blob是二进制数据,因此您可以在Django的request.body中找到它。它的Bytes编码(不是Unicode)。

HttpRequest.body原始的HTTP请求正文为一个字节字符串。这对于以不同于传统HTML表单的方式处理数据非常有用:二进制图像、XML有效载荷等。

票数 2
EN

Stack Overflow用户

发布于 2021-06-11 00:12:14

这很简单,你可以...请阅读以下内容:

代码语言:javascript
复制
#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())

在您的案例中:

代码语言:javascript
复制
def ajax_upload(request):
    ...
    img = Image.open(request.POST["file"].read())
    ...
    return HttpResponse('{"Status":"OK"}', status=200)

PS:我知道,这个问题有点老了,但我也有同样的问题,很快就解决了,但我最初很难通过搜索找到解决方案。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35805257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档