Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Uploading and Saving Files

5.00/5 (2 votes)
14 Oct 2014MIT2 min read 9.8K  
How to upload and save files

In the previous chapter, I showed some code and its properties of how it can be used to save the data from a form to a text (.txt) file. Now it's time for you to understand how and why media files are different from the simple form.

You need to encode the data of the media being sent to the server before it is sent to the server. For that, you use an enctype and set a value to it inside the form element. Like the following, the enctype attribute of the form is being evaluated to multipart/form-data.

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

Now, when the form will be submitted, everything in it will be first encoded to the relative type and then sent to server. Please note that the files (such as images, audio, video) need to be encoded so that the server can process on them.

Now create the form in the page as:

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

Now when this form will be submitted, the image will be submitted along with the data. Note the accept attribute, I have specified image in it, which will force the browser to only select the image (.jpg, .png etc) files not others such as audio (.mp3, .wav, etc.) and others. 

Now let's get to the server-side code:

JavaScript
if (IsPost) {
      int numberOfFiles = Request.Files.Count;
      for(int i =0; i < numberOfFiles; i++) {
          var uploadedFile = Request.Files[i];
          if (uploadedFile.ContentLength > 0) {
              fileName = Path.GetFileName(uploadedFile.FileName);
              fileSavePath = Server.MapPath("~/App_Data/UploadedFiles/" +
                fileName);
              uploadedFile.SaveAs(fileSavePath);
          }
       }
   }

A Little Elaboration

Now let's get the knowledge of the above code, and let's understand how it works.

You might be familiar with loops and variables upto now. This code makes use of that thing. You will be looping through the images that were selected, but note that this is required only when you are using multiple attributes for the form input element such as:

HTML
<input type="file" name="image" accept="image/*" multiple />

Otherwise, you don’t require that.

Now, the first code that is a request to count the files that were selected. Then it counts their value and uses it as a condition inside a loop. Then after that, it goes back and keeps getting each file and saves it to the server using SaveAs. Note that in this code, we are using UploadedFile variable for each of the media files that is being sent. You can try to edit the code and see how it works. Good luck with it!

License

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