最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AJAX DJango Get files from multiple file field - Stack Overflow

programmeradmin2浏览0评论

I'm doing multiple file upload with AJAX and DJango and I have problem. How to get files from field input and push them to data ? HTML:

<form id="add_photos" method="post" action="" enctype="multipart/form-data">

  {% csrf_token %}
  <input type="file" name="file[]" multiple id="files">

  <input type="submit" name="submit" value="Submit" />

</form>

JS:

function formSubmit(e) {
      e.preventDefault();

      $.ajax({
        method: 'POST',
        data: form.serialize(),
        url: '.',
        success: function(data) {
          console.log(data);
        },
        error: function (data) {
          console.log(data);
        }
      });
    }

I'm doing multiple file upload with AJAX and DJango and I have problem. How to get files from field input and push them to data ? HTML:

<form id="add_photos" method="post" action="" enctype="multipart/form-data">

  {% csrf_token %}
  <input type="file" name="file[]" multiple id="files">

  <input type="submit" name="submit" value="Submit" />

</form>

JS:

function formSubmit(e) {
      e.preventDefault();

      $.ajax({
        method: 'POST',
        data: form.serialize(),
        url: '.',
        success: function(data) {
          console.log(data);
        },
        error: function (data) {
          console.log(data);
        }
      });
    }
Share Improve this question asked Feb 16, 2018 at 14:40 CariwebCariweb 811 silver badge6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

See below an example using FormData. But please note it may not work on old IE browsers (I think 8, 9 won't work).

<input type="file" id="upload_file" data-import-url="{% url 'upload_file' %}" data-csrf-token="{{ csrf_token }}" multiple>

Then the jQuery:

$("#upload_file").change(function () {

  var url = $(this).attr("data-import-url")
  var data = new FormData();
  $.each($("#upload_file")[0].files, function(i, file) {
    data.append("file", file);
  });
  data.append("csrfmiddlewaretoken", $(this).attr("data-csrf-token"));

  $.ajax({
    url: url,
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'post',
    beforeSend: function () {
      // before send, display loading, etc...
    },
    success: function (data) {
      // success handling...
    },
    error: function () {
      // error handling... 
    }
  });

});

In your view you could get it like this:

uploaded_files = request.FILES.getlist('file')

If you need to support older browsers, the jQuery File Upload is a really good library. I've written a tutorial about multiple files upload using Django + Ajax (using this particular library).

发布评论

评论列表(0)

  1. 暂无评论