[Answer]-Integration jquery upload file plugins with Django form

1👍

One way to upload whole form with all files in it is to send the form to a hidden iframe and read the iframe’s contents for server response. Example code:

<form method="post" action="..." enctype="multipart/form-data" target="iframe-name">
    ...
</form>


<iframe name="iframe-name"></iframe>

You will need to handle the load event on the iframe and use something like this iframe.contentDocument.body.innerHTML to read iframe’s contents (server should return HTML with <body> tag for cross-browser compatibility). Actual iframe element can be dynamically created and hidden using JavaScript.

It’s rather easy to write such plugin, but on the other hand probably some of the upload plugins available on the Internet use this method to upload files.

0👍

You can use a FormData object to upload a file via ajax

function display_message(link, form)
{
    var formData = new FormData(form);
    $.ajax(
    {
        url: link,
        type: 'POST',
        dataType: 'json',
        processData: false,
        contentType: false,
        data: formData,
        success: function(result)
        {
            //form not valid -> displays errors
            if (result.form_errors)
            {
                //append current errors to the html form
                errors=result.form_errors
                for (var key in errors)
                {
                    $("#"+key+"_errors").html('<ul class="errorlist"><li>'+errors[key]+'</li></ul>');
                    //~ alert(key+': '+errors[key]);
                }
            }
            else
            {
            }
        }
    });
}
👤Musa

Leave a comment