File Uploader in ASP.NET and ASP.NET MVC

A class to upload files in ASP.NET and ASP.NET MVC.

Introduction

Uploading files is a common scenario and an essential part of many web applications. Here I have created a class which can be used to upload files easily. The uploader class automatically validate all the necessities i.e. validation of upload directory, file extensions etc.

Background

There are plenty of resources on uploading a file in ASP.NET. But I have felt to have a class which would be easier and customizable as well as can perform validation, add prefix and/or suffix to file, encrypt filename, allow choice to overwrite existing file or not and so on. You have to just set the necessary properties you need. You can use it in your ASP.NET as well as ASP.NET MVC application.

Using this Class

Here I am giving an example to use this class.

    Uploader uploader = new Uploader();
 
    uploader.UploadPath     = Server.MapPath("~\Content\Uploads");
    uploader.IsLowerName    = true;
    uploader.IsEncryptName  = false;
 
    uploader.Prefix = "Hello_";
    uploader.Suffix = "_Boom";
 
    uploader.AllowedExtensions.Add(".jpg");
    uploader.AllowedExtensions.Add(".jpeg");
    uploader.AllowedExtensions.Add(".gif");
    uploader.AllowedExtensions.Add(".png");
 
    bool success = uploader.DoUpload("MyFile");
 
    if (success)
    {
        //TODO: Code to handle success
    }
    else
    {
        //TODO: Code to handle failure
    }

Here MyFile is the name of file input type.

 <!-- In Html -->
<input type="file" name="MyFile" id="MyFile" />
<%--In tradition ASP.NET --%>
<asp:FileUpload ID="MyFile" runat="server" />

There is an overload of DoUpload() method. You can either pass the name of the file input as above or HttpPostedFile file object as follows.

HttpPostedFile postedFile = HttpContext.Current.Request.Files["MyFile"] as HttpPostedFile;
uploader.DoUpload(postedFile);

There is also a method by which you can get the HttpPostedFile object by supplying the name of the file input.

HttpPostedFile postedFile = uploader.GetHttpPostedFile("MyFile");
uploader.DoUpload(postedFile);

Configuration Settings

General Settings
UploadPath Full path where file should be uploaded exculding the filename. (Mandatory).
UploadName The name which should be used to save the uploaded file with extension. (Optional).
Prefix The prefix to the filename. (Optional).
Suffix The suffix to the filename. (Optional).
Conditional Settings
MinSize The minimum size of the file in bytes.
MaxSize The maximum size of the file in bytes.
IsOverwrite Whether a file is to overwrite or not.
IsEncryptName Whether a file name is to encrypt or not.
IsLowerName Whether a file name is to lower or not.
IsRemoveSpace Whether space is to be removed from a file name or not.
AllowedExtensions The allowed file extensions with period.
IsRemoveSpace The allowed mime types.
Object Properties
UploadError The object of UploadError class. This class holds error code and error message.
PostedFile The object of PostedFile class. This class holds different informations of posted file.
UploadedFile The object of UploadedFile class. This class holds different informations of uploaded file.
Properties of UploadError Class
Code The error code.
Message The error message.
Properties of PostedFile and UploadedFile Class
FileName The file name with extension.
RawName The file name excluding extension.
FileExtension The file extension with period.
MimeType The file MIME type.
FullPath The absolute path including the file name.
FilePath The absolute path to the file excluding the file name.
FileSize The size of the file in bytes.
IsImage Whether the file is image or not.

If your upload is not succeded then you can get the error code and message by UploadError property. For example:

strring erroCode    = uploader.UploadError.Code;
string errorMessage = uploader.UploadError.Message;

Remember, here error code is not actual http error number. I have used numbers from 1 to 10 so that corresponding message can be customized.

On the other hand, if your upload attempt is succeeded, then you can use information related to the posted file as well as uploaded file by PostedFile and UploadedFile. For example:

string previousFilename = uploader.PostedFile.FileName;
string previousFilePath = uploader.PostedFile.FilePath;
 
string uploadedFilename = uploader.UploadedFile.FileName;
string uploadedFilePath = uploader.UploadedFile.FilePath;

Enjoy this!

Downloads

Download Uploader class here. Uploader Class

Download Uploader Sample In ASP.NET here. Uploader Sample In ASP.NET

Download Uploader Sample In ASP.NET MVC here. Uploader Sample In ASP.NET MVC

Here is the .Net 2.0 version of Uploader class. Uploader Class For ASP.NET 2.0 Application

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit
  • Simpy
  • StumbleUpon
  • DotNetKicks
  • DZone
  • Furl
  • email
  • TwitThis

Tags: , , , , , ,

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

12 Responses to “File Uploader in ASP.NET and ASP.NET MVC”


  1. [...] to VoteFile Uploader in ASP.NET and ASP.NET MVC (1/23/2009)Friday, January 23, 2009 from http://www.blog.valenticabd.comA class to upload files in ASP. NET and ASP. [...]


  2. My website fails upload and doesn’t give any error, the basic project works great but when i’m trying to use master page upload fails. Any solution?


  3. @Hasan, You may be trying to upload a file which size exceeds the default maximum limit. For uploading large file put

    <httpRuntime maxRequestLength="105454" executionTimeout="240" />

    in your web.config file under <system.web>. You can change maxRequestLength and executionTimeout.


  4. I’ve changed the web.config but still the same error (no error, just “Failed”). My Upload directory has write permission. As I said, your example works errorless within same web site solution but not with a master page. I tried to change Form.Enctype = “multipart/form-data” on page_load but nothing changes.


  5. @Hasan, I think you are using uploader.DoUpload("MyFile") to upload your file, where “MyFile” is the ID of the FileUpload control i.e.
    <asp:FileUpload ID="MyFile" runat="server" />

    But in case of master page and content place holder, you know ASP.NET automatically change the ID of the control as, for example: ctl00$ContentPlaceHolder1$MyFile.

    So to ensure the class working you have to use uploader.DoUpload("ctl00$ContentPlaceHolder1$MyFile"). In debug mode if you try quick watch for Request.Files["ctl00$ContentPlaceHolder1$MyFile"] you will see the what’s happening.

    Hope this will help. Let me know. Thanks.


  6. Okay, that was the problem, the name of the control. Thanks a lot and sory for keeping you busy for a while :)


  7. Hi, how are you? i found you through twitter. i’m also from bangladesh. :)

    this HTML things appear very hard to understand to me. so, i wouldnt dare to comment on this issue.

    best of luck.



  8. Hello there! pretty good work man!

    I’m trying to do the same with MVC but in castle mono rail. The solution you provide could be able to work on vs 05 with mono rail?

    Thanx for your work!


  9. Just an update… i could be able to use the class on mono rails… =)

    But i have problems trying to upload more than 1 file :(


  10. @Hasan Thanks for notifying the issue. It’s the problem of the plugin “post2pdf” that I’ve been using. May be something doesn’t supported by the plugin; so causing error.


  11. @Mau As I mentioned this class is not dependent on MVC. You can try the version 3.5 as well as version 2.0 of the class. Hope it will work in castle mono rail (although I’ve not used that :( ). Thanks.

Leave a Reply