Question

I have next problem. When I send POST request with form:

<form id="uploadForm" action="/theme/zip/type/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input id="fileInput" class="input-file" name="upload" type="file">
    <input type="submit" value="Upload" />
</form>

Then on server I have code:

print request.FILES

Server printing:

<MultiValueDict: {u'upload': [<InMemoryUploadedFile: ID_12241.zip (application/zip)>]}>

When I do this action step by step in jQuery code:

var content = zip.generate();
var options = {
    url: '/theme/zip/type/',
    data: {
       file: content
    }
};
$('#uploadForm').ajaxSubmit(options);

I have this file in 'file' param in 'request.POST', but 'request.FILES' is empty(). What I do wrong?

Was it helpful?

Solution

Have a look at JQUery Form Plugin, it is capable of uploading files using ajax.

As per the documentation on their website

Browsers that support the XMLHttpRequest Level 2 will be able to upload files seamlessly and even get progress updates as the upload proceeds. For older browsers, a fallback technology is used which involves iframes since it is not possible to upload files using the level 1 implmenentation of the XMLHttpRequest object.

I am using this in my project, you don't have to define any iframe for old browsers. This plugin will automatically do it for you. Below is the sample code to implement ajax file upload -

The HTML file will look like (download and link the jquery.form.js in html file) :-

<form id="uploadForm" method="post" action="/theme/zip/type/"> {% csrf_token %}
    <input type="file" id="fileInput" name="upload"/>
    <button type="submit">Upload</button>
</form>

<script src="jquery-ui.min.js"></script>
<script src="jquery.form.js"></script>

In js file add following code:-

var options = {
    beforeSubmit:showRequest,  // pre-submit callback
    success:showResponse,  // post-submit callback
    resetForm: false        // reset the form after successful submit
};

//uploadForm is the name of your form
$('#uploadForm').submit(function() {
    // inside event callbacks 'this' is the DOM element so we first
    // wrap it in a jQuery object and then invoke ajaxSubmit

    $(this).ajaxSubmit(options);

    // !!! Important !!!
    // always return false to prevent standard browser submit and 
    // page navigation return false;
});

// pre-submit callback 
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it 
    // to a string to display it but the form plugin does 
    // this for you automatically when it submits the data 
    var queryString = $.param(formData); 

    // jqForm is a jQuery object encapsulating the form element. 
    // To access the DOM element for the form do this: 
    // var formElement = jqForm[0]; 

    alert('About to submit: \n\n' + queryString); 

    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the 
    // form submit to continue 
    return true; 
} 

// post-submit callback 
function showResponse(responseText, statusText, xhr, $form)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 

    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 

    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 

    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
        '\n\noutput div should have been updated with the responseText.'); 
} 

Once you click on the submit button .submit() function will be called. This function returns false which is important to prevent browser postback. In this function 2 call back functions are defined.

  1. showRequest will be called when form is about to submit, here you can see all the post data.
  2. showResponse will be called when server returns the response.

On server you will get data in request.FILES. Return a JSON response from server which can be accessed in showResponse function.

OTHER TIPS

Ajax in the traditional sense is XMLHttpRequest, which does not allow you encode and send local files to a server.

The common ways of doing uploading through "ajax" means, is to either use a Flash swf to handle the uploading on the same page, or to use a form that has a target of an invisible 1x1 iframe.

try

http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/

or try http://www.uploadify.com/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top