首页 > 解决方案 > 通过 POST 请求将图像保存到 Django 媒体文件夹

问题描述

我想将通过网络摄像头捕获的图像保存在媒体文件夹下面的 JS 函数 Snapshot in html 拍摄快照并向本地主机服务器发出发布请求。

function snapshot() {
    // Draws current image from the video element into the canvas
    ctx.drawImage(video, 0,0, canvas.width, canvas.height);
    var Pic = document.getElementById("myCanvas").toDataURL("image/png");
    Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "")

    // Sending the image data to Servers
    $.ajax({
    type: 'POST',
    url: 'addface',
    data: '{ "imageData" : "' + Pic + '" }',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (xhr, status, error) {
        alert("Done, Picture Uploaded.");
    },
   });
  }

意见.PY

from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
# Create your views here.


def index(request):
    return render(request, 'index.html')

@csrf_exempt
def add(request):
if request.method == "POST":
    print(request.imagedata)
    return HttpResponse(request.imagedata)
else:
    return HttpResponse('no data')

错误: REQUEST 没有名为“imagedata”的属性,即使发布请求将图像数据作为 ajax 发布请求的一部分。

我在 settings.py 中配置了媒体文件夹。(基础>静态>媒体)

MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static','media')

标签: djangopython-3.xpostdjango-views

解决方案


如果您想要来自 json 有效负载的数据,您必须阅读request.body.

import json, base64

@csrf_exempt
def add(request):
    if request.method == "POST":
        payload = json.loads(request.body)
        image_data = base64.b64decode(payload['imagedata'])

对于文件,使用“multipart/form-data”而不是 json 更为常见。那么你就不需要在base64之间进行编码了。使用分段上传时,您可以从request.FILES属性访问 django 视图中的文件。您还需要更改客户端代码。看看FormDataweb api。

https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects


推荐阅读