Click here to Skip to main content
15,885,366 members
Articles / Web Development / HTML

Uploading the Files – HTML5 and jQuery Way!

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
28 Nov 2014MIT6 min read 35.5K   16   11
Uploading the files - HTML5 and jQuery way

Most of the websites use HTML5 and jQuery plugins, to upload files without the user having to send a POST request to the server, which is not a likely way of uploading the files.

Old Way of Uploading Files

In old days, people liked to create a simple HTML form, and assign the encytype to it, that would let them select a file and then they would click on the Submit button which would then take them to a new page, where they would be shown the message, “Your photos have been uploaded” – or an error message telling them that there was an error. This is a bit irritating and awkward, because the user uploaded more like 5 photos among which one got an error, and the remaining 4 were also discarded and the user was told after 2 minutes to upload the 4 photos only and not that one particular image. Sometimes, connection is lost and other stuff!

New Ways Of Uploading the Files

The web is changing, and there are a lot of new ways in which the user can upload the image or any of his files to the server, without having him to submit the form as he did back in 90s.

Using the iframes

Well before HTML5, people used hidden iframes to target the form to be uploaded from, the iframe is just another HTML document embedded in your main HTML document, that if even navigated to any other web page doesn’t trigger any navigation event in the main page. Which means that if the form is submitted through an iframe the main page the user stands on is never submitted. But he can still view the results and other associated data, such as form elements and the result window.

HTML5 and JavaScript

But these are also old now, JavaScript is strong enough to upload your files, and using HTML5 you can easily work your way with the validations of files too. You can manage which file to upload and which one to reject. This option also minimizes the chances of error for any file that were triggered in the old methods and the user was informed of those errors after he uploaded all of the HTTP request data.

In JavaScript, we can shorten down the code for creating an Ajax request – An Ajax request is an asynchronous request to the server to get some resources from the server and display it in the web page without needing to reload the web page. This technology (Ajax) enables us, to get any data to the web server without having to use the POST requests and reload the web page for the new content, and similarly it also enables us to send any data to the server – such as files, images and other data – to the web server. This makes the uploading of the content an easy method.

jQuery Code

In this blog post, I will be using jQuery – why? because I love jQuery, it is shorter in syntax and looks cool, but remember it is slower than pure JavaScript because it is just a library that runs over JavaScript but the difference is barely noticable – to send the Ajax requests to the server, along with the file data that we want to be uploaded.

The first stage is to create the HTML form that will be capturing any of the files that the user wants to upload to the server. For example, the following code would be an example of the HTML form that will accept the files from the user and contains a simple button from which he will upload the files – I know, button is an old method, but in this method, this button won’t perform the built-in function, it will be captured by JavaScript and the page will stay where it is all using the JavaScript watch the jQuery code for more on this section.

HTML
<form method="post" id="form" enctype="multipart/form-data">
  <input type="file" name="file" />
  <input type="submit" value="Upload" />
</form>

Above is the example for the form. Now once we will look into 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; multiple files are not allowed yet) file and the Upload button will be used to trigger the main function.

The following is the JavaScript (jQuery) code that will capture the event and send a request along with the file.

JavaScript
$(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.');
           }
       });
    });
 });

.. in the above code, there is an element where the result is being rendered. That was like this:

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

.. in this element, you will be showing the process that is currently going on.

  1. First of all – It will show a File is being uploaded… message in this paragraph.
  2. After the upload.
    If the file was uploaded, a success note will be shown otherwise an error message will be displayed to the user.

How will the button not submit the form by using a POST request? That is overridden by the code, in the second line inside the event handler. event.preventDefault(); in this code line, the default behaviour that will be triggered is overridden. Meaning that the page won’t be loaded again by a POST request, instead only that code will execute that we want – the Ajax code in the code block.

ASP.NET Method to Capture and Make Sure the Request was Having a File

You can use the following code of ASP.NET, that will make sure that the file is attached with the request, and then follow on to the saving process and so on. For example, this code:

C#
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 above code will work for any image or any file type. There is no validation until now, you can attach your own validations depending on the Mime type or the size of the file that was attached the request.

Omitting the enctype

Oh well, I said that after the jQuery code, I will explain how you can omit the enctype attribute – or if you even miss writing the enctype, the result will be valid to upload the file – is that when you’re using the FormData object, to send the data, it makes the form behave as if the enctype of the form was set to the multipart/form-data (which is required to encode the files and tranfer them on HTTP). ‘

That is why, even if you miss this part and are using the FormData, you will see that the images are being uploaded to the server.

Points of Interest

HTML5 and jQuery are widely used frameworks to upload the files using Ajax request to the web servers making it easier to control the file types to be uploaded, validating the maximum file size to be uploaded and some other particular validation can be handled easily on the client-side making it easier for the user to perform uploading tasks fast.

FormData is an object that once used makes it easy to encode the files and other data as if the form’s enctype was set to the multipart/form-data. This is used (and is required) to upload files on the server through HTTP requests.

You can prevent any default method to be executed upon any element or control, using the JavaScript’s preventDefault() method.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer
Pakistan Pakistan
Afzaal Ahmad Zeeshan is a computer programmer from Rabwah, Pakistan, currently living in The Netherlands, likes .NET Core and Node.js for regular everyday development. Afzaal Ahmad works at Adyen as a Developer Advocate.

He is an expert with Cloud, Mobile, and API development. Afzaal has experience with the Azure platform and likes to build cross-platform libraries/software with .NET Core. Afzaal is an Alibaba Cloud MVP, twice he has been awarded Microsoft MVP status for his community leadership in software development, four times CodeProject MVP status for technical writing and mentoring, and 4 times C# Corner MVP status in the same field.

Comments and Discussions

 
QuestionHaving Issue Pin
Member 1150387916-May-17 8:10
Member 1150387916-May-17 8:10 
QuestionRequest Pin
JH643-Dec-14 13:47
JH643-Dec-14 13:47 
AnswerRe: Request Pin
Afzaal Ahmad Zeeshan4-Dec-14 7:22
professionalAfzaal Ahmad Zeeshan4-Dec-14 7:22 
QuestionThanks! Pin
ROGII3-Dec-14 10:41
ROGII3-Dec-14 10:41 
AnswerRe: Thanks! Pin
Afzaal Ahmad Zeeshan4-Dec-14 7:21
professionalAfzaal Ahmad Zeeshan4-Dec-14 7:21 
QuestionSystem security won't allow me to download from dropbox. Pin
Member 111588902-Dec-14 4:26
professionalMember 111588902-Dec-14 4:26 
AnswerRe: System security won't allow me to download from dropbox. Pin
Afzaal Ahmad Zeeshan2-Dec-14 4:59
professionalAfzaal Ahmad Zeeshan2-Dec-14 4:59 
AnswerRe: System security won't allow me to download from dropbox. Pin
Alexandro Ramos Rodríguez2-Dec-14 8:39
Alexandro Ramos Rodríguez2-Dec-14 8:39 
AnswerRe: System security won't allow me to download from dropbox. Pin
Afzaal Ahmad Zeeshan2-Dec-14 8:42
professionalAfzaal Ahmad Zeeshan2-Dec-14 8:42 
Questionthnkas Pin
Uthman Rahimi1-Dec-14 5:08
professionalUthman Rahimi1-Dec-14 5:08 
AnswerRe: thnkas Pin
Afzaal Ahmad Zeeshan1-Dec-14 5:16
professionalAfzaal Ahmad Zeeshan1-Dec-14 5:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.