django:当我使用ajax发送到服务器时,如何在formdata中获取每个文件?

时间:2015-10-17 03:48:15

标签: python ajax django file-upload

我正在尝试将多个文件上传到服务器,但它只收到一个文件......所以,我做错了。有人可以帮助我吗?!

我正在使用ajax尝试上传多个文件

这是我的view.py:

@csrf_protect
 def car(request):
    title = 'success'
    data = request.FILES['images[]']
    b = products(name ="car", image = data)
    b.save()
    print data
    return HttpResponse(title)

这是我的ajax:

<script type="text/javascript">
        $(document).ready(function () {
            var input = document.getElementById("images"),
                formdata = false;

            if (window.FormData) {
                formdata = new FormData();
                document.getElementById("btn").style.display = "none";
            }

            function showUploadedItem (source) {
              var list = document.getElementById("image-list"),
                  li   = document.createElement("li"),
                  img  = document.createElement("img");
                img.src = source;
                li.appendChild(img);
                list.appendChild(li);
            }

            if (input.addEventListener) {
                  input.addEventListener("change", function (evt) {
                    var i = 0, len = this.files.length, img, reader, file;

                    document.getElementById("response").innerHTML = "Uploading . . ."

                    for ( ; i < len; i++ ) {
                      file = this.files[i];

                      if (!!file.type.match(/image.*/)) {
                        if ( window.FileReader ) {
                          reader = new FileReader();
                          reader.onloadend = function (e) { 
                            showUploadedItem(e.target.result);
                          };
                          reader.readAsDataURL(file);
                        }
                        if (formdata) {
                          formdata.append("images[]", file);
                        }
                      } 
                    }
                    if (formdata) {
                        var title1 = document.getElementById("title").value
                        formdata.append('title', title1)
                        $.ajaxSetup({ 
                               beforeSend: function(xhr, settings) {
                                   function getCookie(name) {
                                       var cookieValue = null;
                                       if (document.cookie && document.cookie != '') {
                                           var cookies = document.cookie.split(';');
                                           for (var i = 0; i < cookies.length; i++) {
                                               var cookie = jQuery.trim(cookies[i]);
                                               // Does this cookie string begin with the name we want?
                                               if (cookie.substring(0, name.length + 1) == (name + '=')) {
                                                   cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                                                   break;
                                               }
                                           }
                                       }
                                       return cookieValue;
                                   }
                                   if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                                       // Only send the token to relative URLs i.e. locally.
                                       xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                                   }
                               } 
                          });   
                        $.ajax({
                            url: "/thunghiem/chaychoi2",
                            type: "POST",
                            data: formdata,
                            processData: false,
                            contentType: false,
                            success: function (res) {
                              document.getElementById("response").innerHTML = res; 
                            }
                        });
                    }
                  }, false);
            }
        })
    </script>

1 个答案:

答案 0 :(得分:0)

你可以试试这个

request.FILES.getlist('images') #or images[] as you done in javascript

将获得一个列表。然后在其上应用for循环。