Users Pricing

articles

home / developersection / articles / html5 and jquery way for uploading files

HTML5 and JQuery Way for Uploading Files

Anonymous User 4407 20 May 2015 Updated 13 May 2026

In this article I’ll explain how to use JQuery and HTML5 toupload files.
 

Introduction:

Most websites use HTML5 and jQuery plugins to upload fileswithout requiring the user to send a POST request to the server but that is nota productive way to upload files.

Prior way to upload files:

In the old days, people would create a simple HTML form and assign theenctype to it. That would let them select a file and then they will click onthe Submit button that would then take them to a new page, where they will beshown the message, “Your photos have been uploaded”, or an error messagetelling them that there was an error. This is a bit irritating and awkward,because the user uploaded more like 5 photos among them with one getting anerror and the remaining 4 were also discarded and the user was told after 2minutes to upload the 4 photos only and not that one specific image. Sometimes,the connection is lost and other stuff!
 

Newway to upload files:

The web is changing and there are many new ways for a user to upload an imageor file to the server, without having to submit the form as he did back in 90s.
 

Usingiframes:

Well before HTML5, people used hidden iframes to target the form to beuploaded from. The iframe is just another HTML document embedded in your mainHTML document that if even navigated to any other web page it doesn't trigger anavigation event in the main page. Which means that if the form is submittedusing an iframe then the main page the user is at is never submitted. But hecan still view the results and other associated data, such as form elements andthe result window.
 

HTML5and JavaScript:

But these are also old now, JavaScript is strong enough to upload yourfiles and using HTML5 you can easily work your way with the validations offiles too. You can manage which file to upload and which one to reject. Thisoption also minimizes the chances for error for any file that was triggered inthe old methods and the user was informed of those errors after he uploaded allof the HTTP request data.
In JavaScript, we can shorten the code for creating an Ajax request. AnAjax request is an asynchronous request to the server to get some resourcesfrom the server and display it in the web page without needing to reload theweb page. This technology (Ajax) enables us to get data to the web serverwithout having to use the POST requests and reload the web page for the newcontent and similarly it also enables us to send any data to the server, suchas files, images and other data, to the web server. This makes the uploading ofthe content easy.
 

jQuerycode:


In this article I will be using jQuery; why? Because I love jQuery, itis shorter in syntax and looks cool, but remember it is slower than pureJavaScript because it is just a library that runs over JavaScript but thedifference is barely noticeable. Ajax sends requests to the server, along withthe file data that we want to be uploaded.
The first stage is to create the HTML form that will be capturing any ofthe file that the user wants to upload to the server. For example, thefollowing code would be an example of the HTML form that will accept the filesfrom the user and contain a simple button from which he will upload the files.I know, a button is an old method, but in this method this button won't performthe built-in function, it will be captured by JavaScript and the page will staywhere it is all using the JavaScript. Watch the jQuery code for more on thissection.

<form method="post" id="form" enctype="multipart/form-data">  

   <input type="file" name="file" /> 

   <input type="submit" value="Upload" /> 

</form>

The preceding is the example of the form. Now once we lookinto the jQuery code, we will be able to omit the enctype=”multipart/form-data”part too. Until then, this form, as it stands, will accept a single (multiplefiles are not allowed yet) file and the Upload button will be used to triggerthe main function.
The following is the JavaScript (jQuery) code that will capture the event andsend a request along with the file.

<script>
        $(document).ready(function () {
            // On the document ready  
            $('input[type=submit]').click(function () {
                // Before the request starts, show the 'Loading message...'                 $('.result').text('File is being uploaded...');
                event.preventDefault();
                // On the click even,  
                var formData = new FormData($('#form')[0]);
                $.ajax({
                    type: 'POST',
                    processData: false,
                    contentType: false,
                    data: formData,
                    success: function (data) {
                        // The file was uploaded successfully...                         $('.result').text('File was uploaded.');
                    },
                    error: function (data) {
                        // there was an error.  
                        $('.result').text('Whoops! There was an error in the request.');
                    }
                });
            });
        });
   </script>

In the preceding code, there is an element where the resultis being rendered. That was like this:

<p class="result"></p>

In this element you will be showing the process that iscurrently going on.

  •   First of all, it will show in this paragraph amessage that a file is being uploaded.
  •   After the upload, the success message will bedisplayed in the paragraph.

If the file was uploaded, a success note will be shown otherwisean error message will be displayed to the user.
 

How will a button not submit the form using a POST request? 

That isoverridden by the code, in the second line inside the event handler.event.preventDefault(); in this code line, the default behavior that will betriggered is overridden. Meaning that the page won't be loaded again by a POSTrequest, instead only that code will execute that we want, the Ajax code in thecode block.
 

ASP.NET method to capture and make sure the request has a file

You can use the following code of ASP.NET to ensure the file is attachedwith the request and then follow on to the saving process and so on. Forexample this code:

files =Request.Files.Count;  
        if(files > 0) {  
            // Files are sent!  
            for (int i = 0; i < files; i++) {                var file = Request.Files[i];  
                // Got the image...  
               string fileName =Path.GetFileName(file.FileName);  
                // Save the file...  
               file.SaveAs(Server.MapPath("~/" + fileName));  
            }        }

 The preceding code will work for any image or any file type.There is no validation until now, you can attach your own validations dependingon the MIME type or the size of the file that was attached to the request.

Omittingthe enctype:

Oh well, I said that after the jQuery code I will explain how you canomit the enctype attribute, or if you even miss writing the enctype the resultwill be valid to upload the file. When you're using the FormData object to sendthe data, it causes the form to behave as if the enctype of the form was set tothe multipart/form-data (that is required to encode the files and transfer themon HTTP).
That is why, even if you miss this part and are using the FormData, you willsee that the images are being uploaded to the server.
 

Points of Interest:

HTML5 and jQuery are widely used frameworks to upload the files using anAjax request to the web servers making it easier to control the file types tobe uploaded, validating the maximum file size to be uploaded and some otherspecific validation can be handled easily on the client-side making it easierfor the user to do uploading tasks quickly.
FormData is an object that, once used, makes it easy to encode the files andother data as if the form's enctype was set to the multipart/form-data. This isused (and is required) to upload files on the server using HTTP requests.
You can prevent any default method to be executed upon any element or control,using the JavaScript's preventDefault() method

Also check all other articles on HTML 5 here


I am a content writter !