Django接收JQuery提交的图片文件,亲测能用

url.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Demo.view import * # 项目叫Demo
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>

猜你喜欢

转载自blog.csdn.net/dscn15848078969/article/details/120444494