3

This is the minimal declaration for the HTML in order to upload a file in Blobstore in the upload_url. What is required with this solution is required to click the Submit button in order the content to be submitted and get redirected. How can I do the post in the background with javascript or jQuery without losing the enctype?

<form id="upload_file" action="{{upload_url}}" enctype="multipart/form-data" method="post">
    <input type="file" name="file">
    <input type="submit" name="submit" value="Submit">
</form>
Lipis
  • 21,388
  • 20
  • 94
  • 121
topless
  • 8,069
  • 11
  • 57
  • 86

1 Answers1

4

The jQuery Form plugin allows you to submit multipart forms in the background with Ajax.

Example:

$('#upload_file').submit(function() { 
    var options = { 
        clearForm: true        // clear all form fields after successful submit 
    }; 
    $(this).ajaxSubmit(options);
    return false; 
});

$('[name=submit]').click(function(){
    $('#upload_file').submit();        
});

Making this work silently requires that you replace your 'submit' input with a 'button' input:

<form id="upload_file" action="{{upload_url}}" enctype="multipart/form-data" method="post">
        <input type="file" name="file">
        <input type="button" name="submit" value="Submit">
</form>
Kevin P
  • 1,655
  • 10
  • 16
  • P I have this working but what I want to avoid is clicking the submit button. Since I have chosen the file I would like to be automatically submited - updated without clicking any button. – topless Jun 21 '11 at 17:37
  • Try this: $('[name=file]').change(function(){ $('#upload_file').submit(); }); – Kevin P Jun 21 '11 at 17:45
  • no luck when I select the file it doesn't look like it triggers .change() – topless Jun 21 '11 at 18:39
  • 1
    What version of jQuery are you using? Looks like the .change trigger will only work properly on the file input with 1.4.2 or above. Check out this [related question](http://stackoverflow.com/questions/2993946/any-alternative-to-jquery-change-to-detect-when-user-selects-new-file-via-dialo). – Kevin P Jun 21 '11 at 18:55