Philip007
Philip007

Reputation: 3230

HTML5 file upload: what should be append to FormData

This post looks promising, but I can't figure out what is blobFile in the code? Where can I get this variable?

How to upload a file using jQuery.ajax and FormData


Extra question:

I assume that FormData object contains data in ALL input fields including file input. But it seems not the case. Otherwise we don't need to append the file data to FormData. Could anyone explain why file input is not included in the FormData?

Also, I use Django backend, which by convention access uploaded files in request.FILES. How can I put file data in request.FILES rather than request.POST with $.ajax()?

EDIT I just figured out that NOTHING is in my request.POST and formData in empty. can't figure out why.. Here is relevant code:

// html

<form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
    <span class='file-name' id='file-name-1'>FILE 1</span>
    <input type="file" id='id_image'>
    <input class="browse-click" type="button" value="+"/>
    <input id="send" type="submit" value="change">
</form> 

// js

<script>
    // when button is clicked, the file browser opens
    $('.browse-click').on("click" , function () {
        $('#id_image').click();
    });

    // upload file async when file is selected in file browser
    $('#id_image').on('change', function () {
        var currentpath = window.location.pathname;
        var formData = new FormData($('form')[0]);
        formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
        $.ajax({
            url: currentpath,  //server script to process data
            type: 'POST',
            xhr: function() {  // custom xhr
                var myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){ // check if upload property exists
                    myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
                }
                return myXhr;
            },
            data: formData, 
            cache: false,
            contentType: false,
            processData: false
        });
    });

    function progressHandlingFunction(e){
        if(e.lengthComputable){
            $('progress').attr({value:e.loaded,max:e.total});
        }
    }
</script>

Upvotes: 1

Views: 7494

Answers (1)

Musa
Musa

Reputation: 97717

A FormData data object can be instantiated with a form element or without.
If it is instantiated with a form element all the fields in the form will be automatically added to the form data object.
If it isn't (which is the case in the question you linked to) then you have to add all the fields to the form data manually with the append method.
blobFile is most likely a Blob, you can also use Files which you can get from file inputs.

Upvotes: 1

Related Questions