简体   繁体   中英

Upload file with plain AJAX/JS and Django

this is my popup form

<div class="popup media-upload-form">
   <div class="border cf">
     <div class="close">X</div>
   </div>
  <form class="cf" action="" method="POST" enctype="multipart/form-data">
    {% csrf_token %}

    <!-- {{ form.as_p }} this is what i use, just putting plain html to show you all inputs -->
    <p>
      <label for="id_audio">Audio:</label>
      <input type="file" name="audio" required id="id_audio" />
    </p>
    <input class="button" type="submit" value="Upload" />
  </form>
</div>

this how i used to do it without ajax

def upload_media(request):
    if request.method == 'POST':
        form = forms.MediaForm(request.POST, request.FILES)
        if form.is_valid():
            media_file = form.cleaned_data['audio']
            media = models.PlayerMedia()
            media.user = request.user
            media.title = str(media_file)
            media.description = 'good song'
            media.media = media_file
            media.save()

        return HttpResponse('done')

file is coming from requets.FILES['filename'] and that's the problem, i don't know how to send file from js to django view. JQuery has some plugins but i want to do it without any libraries.

this is what i have so far

var uploadForm = document.querySelector('.media-upload-form form');
var fileInput = document.querySelector('.media-upload-form form #id_audio');

uploadForm.onsubmit = function(e) {
    e.preventDefault();

    var fileToSend = fileInput.value; // this is not it
}

so how do i get reference to selected file and send it with ajax to Django for processing?

I got it!

Turns out, i needed a FormData object to send files, so i get file out of input with files property, and just created FormField put in file with append function and send as regular data, here's what it looks like

var mediaFile = fileInput.files[0];
var formData = new FormData();
formData.append('media', mediaFile);

request.send(formData); // done

and then receive it from Django view with request.FILES

def upload_media(request):
    if request.method == 'POST':
        media_file = request.FILES['media']

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