AJAX DJango从多个文件字段获取文件 [英] AJAX DJango Get files from multiple file field

查看:67
本文介绍了AJAX DJango从多个文件字段获取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AJAX和DJango上传多个文件,但遇到了问题.如何从字段输入中获取文件并将其推送到 data ?HTML:

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);
        }
      });
    }

推荐答案

请参见以下使用 FormData 的示例.但请注意,它可能无法在旧版IE浏览器上运行(我认为8、9无法使用).

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>

然后是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')

如果您需要支持较旧的浏览器,那么<​​a href="https://blueimp.github.io/jQuery-File-Upload/" rel="noreferrer"> jQuery文件上传确实是好的图书馆.我编写了有关多个文件的教程使用Django + Ajax (使用此特定库)进行上传.

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).

这篇关于AJAX DJango从多个文件字段获取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆