Click here to Skip to main content
Click here to Skip to main content

Upload files using an HttpHandler

By , 9 Dec 2009
 

Introduction

Using an HttpHandler to upload files can be quite handy while designing multiple file uploads, large file uploads, resumable file uploads, and reporting on the progress of an upload. I’m sure there are many more uses for it. The article does not intend on explaining the implementations of all uses of the HttpHandler in uploading files, but rather explains the code required by the HttpHandler to upload files. That being said, I have still included an example on how to upload multiple files using the HttpHandler with the help of the Jumploader Java applet in the Points of interest section.

Background

After searching around and being unable to find a short, clear, and concise code snippet that could do this, I wrote my own, and would like to share it with anyone who needs it.

Code anatomy

I am assuming you are familiar with the use of an HttpHandler. Once the file is selected with the file upload control, the button does a post to the HttpHandler. The handler processes the request from the button and uses the HttpPostedFile class to receive the uploaded file class and save it on the server. The HttpPostedFile class provides the properties and methods to get information about an individual file and to read and save the file, and belongs to the System.Web namespace of the .NET framework. Most of the code is contained within the ProcessRequest method of the handler. In the ProcessRequest method, we iterate through the Request.Files array and save them to the local folder using the FileSaveAs method of the HttpPostedFile class, it’s that simple. A Response is populated with the status of the upload and sent back to the client.

public void ProcessRequest(HttpContext context)
{
    string filePath = "FileSave//";

    //write your handler implementation here.
    if (context.Request.Files.Count <= 0)
    {
        context.Response.Write("No file uploaded");
    }
    else
    {
        for (int i = 0; i < context.Request.Files.Count; ++i)
        {
            HttpPostedFile file = context.Request.Files[i];
            file.SaveAs(context.Server.MapPath(filePath+file.FileName));
            context.Response.Write("File uploaded");
        }
    }
}

Using the code

  1. Your web site/application will need a user interface such as an ASPX page, a generic HttpHandler, and a web.config configuration file.
  2. On the ASPX page, add a file upload control and a button control, and set the PostBackUrl to point to the handler's type.
  3. <asp:FileUpload ID="FileUpload"  runat="server" />
        <asp:Button ID="But_Upload" runat="server"
                Text="Upload" PostBackUrl=".upl" />
  4. You will then need to configure the handler in the web.config.
  5. <httphandlers>
      <add verb="*" path=".upl"
          type="UploadHttphandler.UploadHandler,UploadHttphandler">
      </add>
    
    </httphandlers>
  6. Lastly, modify the method ProcessRequest in your HttpHandler class to include the code snippet under the code anatomy section.

The download includes a simple file upload control that posts back to the upload handler. You can do the same with whatever interface that you wish to use to upload files. You could also modify the file on receiving it, or generate thumbnails etc., using the file.

Points of interest

Multiple file uploader – You can use Jumploader, a very cool multiple file upload Java applet, with the above code. You will need to include the applet jar file in your project, which can be downloaded from http://jumploader.com/download.html. You will need the following code in the ASPX page to render the applet:

<applet width="600" height="400"
             archive="jumploader_z.jar"
             code="jmaster.jumploader.app.JumpLoaderApplet.class"
             name="jumpLoaderApplet">

    <param value="/.upl" name="uc_uploadUrl" />
</applet>

You can increase the file size being uploaded by adding the following to your web.config. The executionTimeout is in seconds, and maxRequestLength is in bytes.

<httpRuntime executionTimeout="1800" maxRequestLength="100000" />

License

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

About the Author

Ritesh Ramesh
Architect Infosolvex Solutions Inc
Australia Australia
Member
Ritesh is an IT consultant with over ten years of experience in the IT industry varying from consultation, architecture, design, development to technical management. He has a strong background in solutions and applications architecture with a focus on Microsoft’s .Net platform. His area of expertise spans design and implementation of client/server, database and web-based systems. He has worked with C#, ASP.NET 1.1 and 2.0, ADO.NET, Web Services and SQL technology on several enterprise class projects.
 

 

Freedom is not worth having if it does not include the freedom to make mistakes.
Mahatma Gandhi

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionNot Working :(memberSachin Pisal16 May '12 - 10:10 
Is this code working @ your place because
 file.SaveAs(context.Server.MapPath(filePath+file.FileName));
file.FileName : give entire path of selected file and it gives error
The given path's format is not supported.
does not save file
QuestionGoodmemberMember 773936625 Jan '12 - 4:20 
This is a very interesting intro to httphandler with fileupload. It works well and certainly hope you will share more of you'r knowlegde. Thank's
QuestionCan you do this without an aspx file?memberevogli7 Oct '11 - 15:49 
Can you do this with a html file and a HttpHandler? How does that change the code? Thanks
GeneralMy vote is 5memberEhsan Baghaki24 Dec '10 - 8:27 
Thanks dude for your perfect simple demonstration of using http handlers... thanks
General[My vote of 1] yes, totally crap!!memberM8R-3d3rjt125 Dec '09 - 6:37 
the article was trying to tell us the handler will be able to upload multiple files. but how? it doesn't say and does not provide a sample page to do so.
 
if it can only upload one file at a time, why do we need this handler?
GeneralRe: [My vote of 1] yes, totally crap!!memberRitesh Ramesh25 Dec '09 - 23:48 
You should really take the time to read before making an irresponsible comment. The section under Points of interest details how to do this. Also if you did understand the title its about using a httphandler not about uploading multiple files even though that's one of the uses and there is an explanation on how to achieve that.
Jokeok, but newbs need more explaination...memberWilliam Forney15 Dec '09 - 3:27 
The previous comments are awefully whiny, don't you think? This article should maybe include a prerequisite list though... Say, understanding of an HttpHandler for one... Basic knowledge of web forms and how to post a file for two... Oh wait, that's what the title leads one to believe this article is supposed to explain. Nevermind... LOL
GeneralRe: ok, but newbs need more explaination...memberRitesh Ramesh16 Dec '09 - 10:23 
Yeah maybe I miss judged the complexity of the article. But again complexity is so relative. I will in future include a prerequisite list. Thanks!
QuestionWhat is the maximum size u can load?memberG.Srinivasan14 Dec '09 - 19:23 
1.Can you specify what is the maximum size that can be uploaded in this way?
2.I do not want to copy under the web site folder? How do i copy to the file drive?
3. Can i upload multiple files?
4. why did you select httphandler instead of Page or Http module?
AnswerRe: What is the maximum size u can load?memberRitesh Ramesh14 Dec '09 - 22:47 
1.Can you specify what is the maximum size that can be uploaded in this way?
 
>> Maximum is 2 gig for .Net 2.0 But you can modify the code to increase this E.g break the file upload into chunks as suggested by reborn_zhang or you can zip the files depending on the type of file.
 
2.I do not want to copy under the web site folder? How do i copy to the file drive?
 
>> If you mean a folder outside of your web site folder you can do it by using a virtual directory that points to a folder outside the website.
 
3. Can i upload multiple files?
 
>> Yes the article contains an example of this, see Points of interest section there is a cool interface that is free to download that can be used with this code.
 
4. why did you select httphandler instead of Page or Http module?
 
>> The httphandler has no overhead of Page life-cycle, direct manipulation of the request/response, gives you greater flexibility over customizing your upload code E.g:- say you want to create thumbnails for uploaded images. Again HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request which is unwarranted under this particular circumstance. Again you can still use the other two but from a coding perspective you can see the simplicity in using the httphandler for this particular task.
Questioncan use multi thread to upload?memberreborn_zhang9 Dec '09 - 7:44 
devide the file into pieces and upload. the server would reconstructure the files.
GeneralerrormemberNitin Sawant9 Dec '09 - 0:45 
unable to upload files greater than 4mb, pls help
 
=============
NITIN SAWANT
=============

GeneralRe: errormemberRitesh Ramesh9 Dec '09 - 0:52 
Are you getting the error using the code in the article? Can you provide more information? It looks like you will need to increase the
maxRequestLength of your Request
GeneralRe: errormemberNitin Sawant9 Dec '09 - 0:53 
yes
 
=============
NITIN SAWANT
=============

GeneralRe: errormemberRitesh Ramesh9 Dec '09 - 0:59 
Add the following in the system.web section of your web.config file
 
<httpRuntime executionTimeout="1800" maxRequestLength="100000" />
GeneralMy vote of 1memberMichael E. Jones8 Dec '09 - 23:45 
Lots of stuff missing
GeneralRe: My vote of 1memberRitesh Ramesh9 Dec '09 - 1:00 
Ive updated the article and am waiting for the editor to update it :(
GeneralMy vote of 1memberRogic8 Dec '09 - 15:43 
total crap
GeneralRe: My vote of 1membergstolarov11 Dec '09 - 4:06 
You are cheerful one aren't you? Looking at your posting history it seems like you have quite a number of vote 1 - "Total crap" type of comments. That doesn't help anyone, discourages people from future posting, insulting and annoying. People spend time and effort to share the information with the rest of us and this should be encouraged, even if you personally think it's not worth it. I wanted just to ignore this article, but your vote makes me vote 5.
I wish there would be a way to ban people like you from this site or at least from posting comments.
GeneralMy vote of 2memberWebnoi8 Dec '09 - 14:58 
This article don't explain how to do the things he said on the introduction. It does not explain nothing. Just show (without explain) how to save a file using a HttpPostedFile.
GeneralRe: My vote of 2memberRitesh Ramesh8 Dec '09 - 23:03 
Not sure what you mean by it does not "explain how to do the things he said on the introduction", was there a particular part of the article I need to explain in detail? I was only quoting the uses of the code in the introduction.
 
Just show (without explain) how to save a file using a HttpPostedFile. There is not much to explain especially since SaveAs method of the HttpPostedFile does pretty much all the saving. HttpPostedFile class is part of the System.Web name space.

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 9 Dec 2009
Article Copyright 2009 by Ritesh Ramesh
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid