Sunday, October 27, 2013

File Upload with jQuery and Ajax

The requirement is simple. I should be able to upload files to the server with jQuery and ajax. Lets get started.
<html>
   <form>
     File Description:<input type="text" id="desc" />
     Choose File:<input type="file" id="chosenFile" />
     <input type="button" id="submitFile" value="submitTheFile" />
   </form>
</html>
Now, the real jQuery stuff
<script type="text/javascript">
    jQuery.noConflict();
    jQuery(document).ready(function() {
        jQuery("#submitFile").click(function() {
            jQuery.ajax({
                url: "[url to be submitted to]",
                type: "POST",
                contentType: false,
                processData: false,
                data: function() {
                    var data = new FormData();
                    data.append("fileDescription", jQuery("#desc").val());
                    data.append("chosenFile", jQuery("#chosenFile").get(0).files[0]);
                    return data;
                    // Or simply return new FormData(jQuery("form")[0]);
                }(),
                error: function(_, textStatus, errorThrown) {
                    alert("Error");
                    console.log(textStatus, errorThrown);
                },
                success: function(response, textStatus) {
                    alert("Success");
                    console.log(response, textStatus);
                }
            });
        });
    });
<script>
Important things to be noted here are
contentType: false,
                processData: false,

contentType will be determined automatically, so we don't have to set that explicitly and processData has to be false, otherwise the data will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". Next important thing is

data: function() {
                    var data = new FormData();
                    data.append("fileDescription", jQuery("#desc").val());
                    data.append("chosenFile", jQuery("#chosenFile").get(0).files[0]);
                    return data;
                    // Or simply return new FormData(jQuery("form")[0]);
                }(),
You can read about FormData here. We basically set the values being submitted. The first parameter is the key and the second parameter is the actual value to be passed. We can get the value of any form field with
jQuery("#desc").val()
expect the files. If we use the same for files, we ll get just the file name instead of the file contents. So, we have to do something like
jQuery("#chosenFile").get(0).files[0]
If we dont want to set individual values and want to pass all the fields in the form, we can simply do
data: new FormData(jQuery("form")[0])
Thats it. Enjoy Ajaxified file upload :)
References:

No comments: