url.py
from Demo.view import *
from django.urls import path
from django.urls.conf import re_path
urlpatterns = [
path('', index),
path('text', text),
]
re_path('', index)
view.py
import json
import base64
import PIL.Image as Image
import matplotlib.pyplot as plt
from io import BytesIO
from django.http import *
from django.shortcuts import *
from django.views.decorators.http import require_http_methods
from Demo.util.common import *
@require_http_methods(["POST"])
def test(request):
body = json.loads(request.body)
img = body['img']
img = base64.b64decode(img)
img = Image.open(BytesIO(img))
plt.imshow(img)
plt.show()
return JsonResponse({
}, status=200)
index.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.4.0.min.js" integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg=" crossorigin="anonymous"></script>
</head>
<body>
<input id="img" name="img" type="file" accept="image/bmp, image/jpeg, image/png, image/jpg" AllowImgFileSize=70; />
<button id="submit" type="submit" onclick="post()">submit</button>
</body>
<script>
function post() {
var reader = new FileReader();
reader.readAsDataURL(document.getElementById('img').files[0]);
reader.onload = function (e) {
var data = e.target.result;
$.ajax({
type: "POST",
url: "/test",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
img: data.replace(/^data:image\/\w+;base64,/, "")}),
dataType: "json",
success: function (message) {
},
error: function (message) {
}
});
}
}
</script>
</html>