如何使用django和ajax在屏幕上显示上传的图像

时间:2019-06-07 11:24:49

标签: ajax django image upload

我正在尝试使用ajax在django中上传图像并将其保存在指定的路径中。图片已上传并保存,但问题是它没有显示在模板中。

我将MEDIA ROOT和Media URL添加到设置文件 我创建一个模型 我在urls文件中创建一个路径 我在视图文件中创建一个函数 我用html创建模板,并使用ajax和jquery。

models.py

class photo(models.Model):
    title = models.CharField(max_length=100)
    img = models.ImageField(upload_to = 'img/')

urls.py

from django.contrib import admin
from django.urls import path, include
from.views import *
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home2),
    path('upload/', upload),

views.py

from django.shortcuts import render,redirect

from django.http import HttpResponse,JsonResponse
from testapp.models import *

import json as simplejson

def upload(request):
    if request.method == 'POST':
        if request.is_ajax():
            image = request.FILES.get('img')
            uploaded_image = photo(img = image)
            uploaded_image.save()

    return render(request, 'home2.html')

home2.html

<html>
  <head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
    <script>
        function upload(event) {
            event.preventDefault();
            var data = new FormData($('#ajax').get(0));
            console.log(data)

            $.ajax({
                url: '/upload/', 
                type: 'POST',
                data: data,
                contentType: 'multipart/form-data',
                processData: false,
                contentType: false,
                success: function(data) {
                    alert('success');
                }
            });
            return false;
        }

    </script>
  </head>

  <body>

    <form method="POST" id="ajax"  enctype="multipart/form-data">
        {% csrf_token %}
        Img:
        <br />
        <input type="file" name="img">

        <br />
        <br />
        <button id="submit"  type="submit">Add</button>

    </form>

     <h1> test </h1>
     <h2> {{ photo.title }}</h2>
     <img src="{{ photo.img.url }}" alt="{{ photo.title }}">

  </body>
</html>

我希望看到上传的图像显示在屏幕上,但是在我上传并提交表单后,src图像仍然为空。

2 个答案:

答案 0 :(得分:0)

您应该做几件事,正如我所看到的,您想使用Ajax呼叫,而根本不必拥有<form></form>。另外,例如,您应该从csrfmiddlewaretoken向服务器发送HTTP POST密钥(在payload请求期间)。您应将数据从客户端发送到服务器,服务器将新图像的url发送回去,并应使用DOM更新javascript

html

<html>
  <head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
  </head>

  <body>

        Img:
        <br />
        <input type="file" name="img" id="img">

        <br />
        <br />
        <button id="submit"  type="submit">Add</button>

    <div id="img_div">

    </div>


    <script>
        $('#submit').click(function() {
            event.preventDefault();
            var formData = new FormData();
            $img = $('#img')[0].files[0];
            formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
            formData.append('image', $img);
            $.ajax({
                url: '/upload/', 
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(data) {
                    $('#img_div').append('<img src="'+data['image_url']+'" />')
                }
            });
            return false;
        });

    </script>

  </body>
</html>

python

from django.shortcuts import render,redirect

from django.http import HttpResponse, JsonResponse
from testapp.models import *

import json as simplejson

def upload(request):
    if request.method == 'POST':
        if request.is_ajax():
            image = request.FILES.get('image')
            uploaded_image = photo.objects.create(img=image)
            return JsonResponse({'image_url': uploaded_image.img.url})

    return render(request, 'home2.html')

希望,对您有帮助。

答案 1 :(得分:0)

首先将模板的这些行围绕在div标签下,如下所示:

<div id="photo">
 <h2> {{ photo.title }}</h2>
     <img src="{{ photo.img.url }}" alt="{{ photo.title }}">
</div>

对视图功能进行如下更改:

from django.http import HttpResponse

def upload(request):
    if request.method == 'POST':
        if request.is_ajax():
            image = request.FILES.get('img')
            uploaded_image = photo(img = image)
            uploaded_image.save()
            photo=photo.objects.first()# This will give last inserted photo

    return HttpResponse(photo)

现在在ajax成功函数中添加以下代码:

$("#photo").html('<h2> {{'+data.title+'}}</h2>
     <img src="{{'+data.img.url+ '}}" alt="{{ photo.title }}">')