Click here to Skip to main content
15,878,852 members
Articles / Web Development / ASP.NET

File Uploader in ASP.NET and ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.65/5 (18 votes)
27 Jan 2009CPOL3 min read 85.1K   5.9K   86   20
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 validates 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 the need to have a class which would be easier and customizable as well as 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 applications.

Using this Class

Here I am give an example to use this class:

C#
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.

HTML
 <!-- In Html -->
<input type="file" name="MyFile" id="MyFile" />
ASP.NET
<%--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 shown above or HttpPostedFile file object as follows:

C#
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.

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

Configuration Settings

General Settings
UploadPathFull path where file should be uploaded excluding the filename(Mandatory)
UploadNameThe name which should be used to save the uploaded file with extension (Optional)
PrefixThe prefix to the filename (Optional)
SuffixThe suffix to the filename (Optional)
Conditional Settings
MinSizeThe minimum size of the file in bytes
MaxSizeThe maximum size of the file in bytes
IsOverwriteWhether a file is to overwrite or not
IsEncryptNameWhether a file name is to encrypt or not
IsLowerNameWhether a file name is to lower or not
IsRemoveSpaceWhether space is to be removed from a file name or not
AllowedExtensionsThe allowed file extensions with period
IsRemoveSpaceThe allowed mime types
Object Properties
UploadErrorThe object of UploadError class. This class holds error code and error message.
PostedFileThe object of PostedFile class. This class holds different information of posted file.
UploadedFileThe object of UploadedFile class. This class holds different information of uploaded file.
Properties of UploadError Class
CodeThe error code
MessageThe error message
Properties of PostedFile and UploadedFile Class
FileNameThe file name with extension
RawNameThe file name excluding extension
FileExtensionThe file extension with period
MimeTypeThe file MIME type
FullPathThe absolute path including the file name
FilePathThe absolute path to the file excluding the file name
FileSizeThe size of the file in bytes
IsImageWhether the file is an image or not

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

C#
string erroCode    = uploader.UploadError.Code;
string errorMessage = uploader.UploadError.Message;

Remember, here the error code is not the 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 successful, then you can use information related to the posted file as well as uploaded file by PostedFile and UploadedFile. For example:

C#
string previousFilename = uploader.PostedFile.FileName;
string previousFilePath = uploader.PostedFile.FilePath;

string uploadedFilename = uploader.UploadedFile.FileName;
string uploadedFilePath = uploader.UploadedFile.FilePath;

Enjoy this!

Conclusion

You can see it in my blog.

History

  • 23rd January, 2009: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Bangladesh Bangladesh
Software Engineer, Bangladesh.

Comments and Discussions

 
Questionthanks Pin
güven şahin21-May-14 3:25
güven şahin21-May-14 3:25 
SuggestionImprovement your library Pin
codeproject.ir31-Jul-12 12:34
codeproject.ir31-Jul-12 12:34 
GeneralWell approach Pin
Md. Marufuzzaman23-Aug-09 5:42
professionalMd. Marufuzzaman23-Aug-09 5:42 
GeneralError!Help Pin
Nguyennamhsm26-May-09 23:10
Nguyennamhsm26-May-09 23:10 
GeneralRe: Error!Help Pin
Jahedur Rahman Chowdhury26-May-09 23:53
Jahedur Rahman Chowdhury26-May-09 23:53 
GeneralRe: Error!Help Pin
Nguyennamhsm28-May-09 0:27
Nguyennamhsm28-May-09 0:27 
GeneralRe: Error!Help Pin
Jahedur Rahman Chowdhury28-May-09 2:24
Jahedur Rahman Chowdhury28-May-09 2:24 
GeneralRe: Error!Help [modified] Pin
Nguyennamhsm28-May-09 17:10
Nguyennamhsm28-May-09 17:10 
GeneralRe: Error!Help Pin
Jahedur Rahman Chowdhury28-May-09 19:24
Jahedur Rahman Chowdhury28-May-09 19:24 
It seems you are using my web.config file that was build automatically for version 3.5. Note the error

<providerOption name="CompilerVersion" value="v3.5"/>


in this line. You can replace 3.5 by 2.0 although I'm not sure whether it will work. But it would be better for you to create a new instance of website and use the new Uploader class so that your web.config become compatible with your version i.e. 2.0. Otherwise, converting web.config of version 3.5 to 2.0 requires plenty of modification which will be cumbersome for you, I guess.

Try It.

Mohammad Jahedur Rahman
Senior Software Engineer
Brain Station-23

GeneralRe: Error!Help Pin
Nguyennamhsm28-May-09 21:23
Nguyennamhsm28-May-09 21:23 
GeneralThanks for this peace og code Pin
msheikh200918-May-09 16:59
msheikh200918-May-09 16:59 
GeneralThe code is working good except the upload is empty Pin
hhzj20044-May-09 0:57
hhzj20044-May-09 0:57 
GeneralRe: The code is working good except the upload is empty Pin
Jahedur Rahman Chowdhury4-May-09 1:28
Jahedur Rahman Chowdhury4-May-09 1:28 
GeneralRe: The code is working good except the upload is empty Pin
hhzj20044-May-09 1:57
hhzj20044-May-09 1:57 
GeneralRe: The code is working good except the upload is empty Pin
Jahedur Rahman Chowdhury4-May-09 2:21
Jahedur Rahman Chowdhury4-May-09 2:21 
GeneralRe: The code is working good except the upload is empty Pin
hhzj20044-May-09 3:44
hhzj20044-May-09 3:44 
Generalgreat job Pin
Juergen Gutsch21-Feb-09 0:13
Juergen Gutsch21-Feb-09 0:13 
GeneralDifferences with MVC and non-MVC Pin
Steve Maier27-Jan-09 10:18
professionalSteve Maier27-Jan-09 10:18 
GeneralRe: Differences with MVC and non-MVC Pin
Jahedur Rahman Chowdhury27-Jan-09 17:10
Jahedur Rahman Chowdhury27-Jan-09 17:10 

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.