Django Ajax Image submit

廉价感情. 提交于 2021-01-29 14:58:34

问题


I am trying to upload and save an image file using Django and respond the image itself to use in ongoing javascript functions.

The problem is that the image doesn't get saved, the request.FILES is empty.

When using request.body, I can see that there is not the actual file path, but a C://fakepath.

Because I want the uploaded image to save immediately, I do the post using a jquery ajax call, the data is then saved creating a new Object, then the function should return a success, which it does.

views.py:

    def image_feedback(request):
        if request.method == 'POST':

            image = request.FILES.get('image')

            ImagesUpload.objects.create(
                image = image,
            )

            return HttpResponse('success')

models.py:

    class ImagesUpload(models.Model):
        image = models.ImageField(upload_to=renaming_file)

        def __str__(self):
            return str(self.image)

form_template.html:



<form id="image_form" enctype="multipart/form-data">{% csrf_token %}
  <button class="btn btn-secondary" onclick="$('#id_image').click()">Import Image</button>

  {{ form_image.image }}

  <input id="hidden-submit-img" value="SUBMIT" type="submit" style="visibility:hidden">
</form>

jquery ajax call:

<script>



    $(document).ready(function () {
      // This jquery changes the appearance of the django { form_image }
      var imgElement = $('#id_image');

      imgElement.css('visibility', 'hidden');

      // This function triggers the hidden submit,
      //  which triggers the ajax image request
      imgElement.on({
        change: function () {
          $('#hidden-submit-img').click();
        },
      });
    });


    // This jquery is for the ajax post of the image
    $('#image_form').submit(function (event) {
      event.preventDefault();
      $.ajax({
        data: {
          image: $('#id_image').val(),
          csrfmiddlewaretoken: '{{ csrf_token }}'
        },
        type: "POST",
        enctype: 'multipart/form-data',
        url: "{% url 'website:image-feedback' %}",
        success: function (data) {
          console.log(1);
          console.log(data)
        },
        error: function (data) {
          console.log(0);
        }

      });
    });

    </script>

I think the image can't get saved because the javascript doesnt pass the correct path, but how to solve this?

EDIT:

When changing the event from .submit to .change in the ajax call, the image gets saved and I can see the successful console.log in my browser, BUT the HttpResponse('success') renders a new, empty page containing the word "success" only.

How can I prevent HttpResponse from doing that? Changing the event back to .submit prevents the page from reloading, but the image cant get saved

Here is my new ajax call, the views.py remains unchanged:

// This jquery is for the ajax post of the image

    // Doing it with submit, the image wont get saved, but the request is "success"
    // $('#image_form').submit(function (event) {

    // Doing it with change, the image gets saved successfully, 
    // the console logs the success
    // but the respond loads a new page
    $('#image_form').change(function (event) {
      event.preventDefault();
      $.ajax({
        data: {
          image: $('#id_image').val(),
          csrfmiddlewaretoken: '{{ csrf_token }}'
        },
        enctype: 'multipart/form-data',
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        success: function (data) {          
          console.log(1);
          console.log(data)
        },
        error: function (data) {
          console.log(0);
        }

      });
    });

来源:https://stackoverflow.com/questions/60702993/django-ajax-image-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!