django - 通过 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')
解决方案
如果您想要来自 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 视图中的文件。您还需要更改客户端代码。看看FormData
web api。
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
推荐阅读
- jmeter - 将 JMeter 与 ZAP 工具集成
- angular - 如何在 TypeScript 中同步下拉菜单?
- c# - 如何在应用程序代码中删除 app.config
- ios - 在蒙面的 UIView 周围添加阴影
- machine-learning - 在使用全卷积网络的语义分割中,为什么交叉熵损失优于 L1 或 L2 损失?
- android - android中画布文本的椭圆大小
- node.js - 如何修复 npm ERR!缺少脚本:从反应开始
- ios - CocoaPods 找不到 pod“Alamofire 5.0.0-rc.2”的兼容版本
- visual-studio - 如何降级 Visual Studio 2017 版本?
- javascript - 节点/javascript中的“位置”属性