简体   繁体   中英

Django Multiple Files Upload Using Ajax without forms

I have an aplication in Django 2.0 where one user can upload many images of their diplomas at the same time but also, I need to make this with ajax so the page will not reload.

This is my models.py

class diploma(models.Model):
    user = models.ForeignKey(user, on_delete=models.CASCADE, null=True)
    diploma=models.ImageField(default='nopic.png', null=True)
    def __str__(self):
        return self.diploma

And this is my file input in my template upload.html

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<input type="file" id="images" name="images[]" multiple accept="image/jpg,image/png,image/jpeg,image/gif">
<a onclick="uploadWithAjax()"> Upload Images </a>

If you notice, there's no Form html tag. Just an 'a' link that calls the function uploadWithAjax().

This is my script with the uploadWithAjax() function

function uploadWithAjax()
{
  var files = $('#images')[0].files;
  $.ajax(
  {
    type: "POST",
    url: "/UploadImages/",
    data: "", //I DON'T KNOW WHAT DATA I HAVE TO PUT HERE
    success: function(result)
    {
      alert('IMAGES UPLOADED');
    }
  });
}

I Think I have to send the 'files' variable in the 'data' atribute of ajax, but I'm not sure becouse there are files and dont normal inputs. Please help.

This is my ajax.py file, where I recive the images

def UploadImages(request):
  diplomas = request.FILES['images'] #I don't know if this is correct

I didn't finish the view becouse I don't know how to continue or how to make a register in my bd table for each image I uploaded. Please Help!

function uploadWithAjax() {
  var files = $('#images').prop("files");
  if(files.length > 0) {
      $.ajax({
         type: "POST",
         url: "/UploadImages/",
         data: {"images": files}
         success: function(result) {
             alert('IMAGES UPLOADED');
         }
      });
  }
}

And there, you just passed a list of image files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM