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

ASP.NET File Upload with Progress Bar

By , 20 Jul 2012
 

Introduction 

File upload widget that will display real time file upload progress bar:

FileUploadWithProgrss/Messages.png

Background

This will allow user to upload, download and delete file with classic user interface and without reloading page.

Using the Code

The upload widget includes the following:

  • File Upload interface (Default.aspx)
    • IFRAME (which contains upload engine page UploadEngine.aspx)
    • Upload button (that will allow user to upload file on server)
    • Display statistics for uploading file (Filename, Status, Progress and Transferred Bytes)
    • Grid (that will display list of uploaded files)
    • Hidden field (it will monitor and refresh file list whenever file was successfully uploaded on server)
  • Upload Engine (UploadEngine.aspx)
    • File Upload control

Page Structure (Default.aspx)

FileUploadWithProgrss/PageStructure.png

Upload Engine structure (UploadEngine.aspx)

FileUploadWithProgrss/UploadEngineStructure_.png

Page execution flow

During page loading, it will automatically register click event for Upload button.

FileUploadWithProgrss/PageExecutionFlow_1.png
  1. Choose File to upload
  2. Clicking on Upload button (it will automatically register click event for Upload button)
    • The following function is checking basic validation on client site like
      • File Upload should not be empty
      • File name should be unique
    • Executing (UploadEngine) submit event using JavaScript
    • During execution of (UploadEngine) two processes are executing simultaneously
      • Page will maintain File Upload details in session with the help of UploadDetail class
      • Every 500 milliseconds, the PageMethod will call and display progress of current uploading file with Size and Percentage value
    • Display continuous progress using StartProgress function
  3. FileUploadWithProgrss/PageExecutionFlow_2.png

  4. Display real time progress

    FileUploadWithProgrss/PageExecutionFlow_3.png

  5. Update message based on result, result may from following:
    Success Information Warning Error

    FileUploadWithProgrss/PageExecutionFlow_4.png

  6. The two processes are executing simultaneously on server side are as follows:
    • Upload Engine

      FileUploadWithProgrss/ProcessesExecution_1_.png

    • Default

      FileUploadWithProgrss/ProcessesExecution_2.png

  7. During file upload processes, the following screen would be appear:

    FileUploadWithProgrss/Downloading.png

  8. Following functionality is also available in Grid:

    FileUploadWithProgrss/Delete_DownloadFile.png

  9. I provided classical look and feel (with CSS) and cross browser compatible script (with JavaScript).
  10. The upload widgets are supported by the following browser:

    FileUploadWithProgrss/Browser.jpg

    UPDATED - 2: 

    I have added three new files for saving file in database. 

    • App_Code  
      1. SaveFile.cs  (Logic for saving file database, Attention: modify only database connection)
      2. Result.cs (this will return status success of failed with description)
    • App_Data 
      1. Script.Sql (Database script for creating Table and Stored Procedure) 

    Modified only one file UploadEngine.aspx.cs

    Please add following code after

    if (this.fileUpload.PostedFile != null && this.fileUpload.PostedFile.ContentLength > 0) 
     //START : Saving File in Database
                    SaveFile saveFileInDB = new SaveFile();
                    saveFileInDB.FileName = this.fileUpload.PostedFile.FileName;
                    saveFileInDB.FileExtension = Path.GetExtension(this.fileUpload.PostedFile.FileName);
                    saveFileInDB.FileContent = this.fileUpload.FileBytes;
                    Result Result = saveFileInDB.SaveFileInDB();
                    if (Result.IsError == false)
                    {
                        //File Save in Database Successfully!
                    }
                    else
                    {
                        //Error in Saving File in Database!
                        //Error: Result.ErrorMessage
                        //InnerException: Result.InnerException
                        //StackTrace: Result.StackTrace
                    }
                    //END : Saving File in Database

Points of Interest 

Now I will try to support multiple files upload feature.  

History  

If you find some issues or bugs with it, just leave a comment or drop me an email. If you make any notes on this, let me know that too so I don't have to redo any of your hard work.

1.                      Initial Upload

2.  21-07-12       Add functionality to uploaded file in Database also

Please provide a "Vote", if this would be helpful.  

License

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

About the Author

Sunasara Imdadhusen
Software Developer (Senior) Infostretch Ahmedabad-Gujarat
India India
Member
Aspiring for a challenging carrier wherein I can learn, grow, expand and share my existing knowledge in meaningful and coherent way.

sunaSaRa Imdadhusen
+91 99095 44184
 
AWARDS:
  1. 1st Best Asp.Net article of SEP 2010
  2. 2nd Best Asp.Net article of MAY 2011
 
Read More Articles...

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   
GeneralMy vote of 5memberAnup Shetty15 May '13 - 21:00 
Fantastic article.Wonderful!
GeneralRe: My vote of 5professionalSunasara Imdadhusen15 May '13 - 21:18 
Thank you very much for your appreciation.Thumbs Up | :thumbsup:

sunaSaRa Imdadhusen
+91 99095 44184

GeneralMy vote of 5memberJOE MIS21 Apr '13 - 15:50 
excellent!!
GeneralRe: My vote of 5professionalSunasara Imdadhusen19 May '13 - 19:57 
Thanks for your appreciations

sunaSaRa Imdadhusen
+91 99095 44184

QuestionPROBLEM CONVERITNG IN VB.NETmemberMember 997229814 Apr '13 - 21:21 
this code works great in c#. but when i convert it in vb.net ,it gives error in <script type="text/javascript">
function pageLoad(sender, args) {

window.parent.register(
$get('<%= this.form.ClientID %>'),
$get('<%= this.fileUpload.ClientID %>')
);
}
</script>
 
Error 1 'this' is not declared. It may be inaccessible due to its protection level.
AnswerRe: PROBLEM CONVERITNG IN VB.NETmemberSunasara Imdadhusen14 Apr '13 - 21:26 
Following are the VB.Net version
 
<script type="text/javascript">
function pageLoad(sender, args) {
 
window.parent.register(
$get('<%= Me.form.ClientID %>'),
$get('<%= Me.fileUpload.ClientID %>')
);
}
</script>

sunaSaRa Imdadhusen
+91 99095 44184

Questionthank youmemberkazemtnt26 Mar '13 - 8:35 
thank you very good
AnswerRe: thank youmemberSunasara Imdadhusen22 Apr '13 - 0:10 
Thank you very much

sunaSaRa Imdadhusen
+91 99095 44184

QuestionPerfect tutorialmemberLedZepelin8 Mar '13 - 5:17 
Really good stuff !
You are the only one to propose such a clear stuff !
Thank you very much
AnswerRe: Perfect tutorialmemberSunasara Imdadhusen14 Apr '13 - 21:28 
Thank you very much for your appreciations.Thumbs Up | :thumbsup:

sunaSaRa Imdadhusen
+91 99095 44184

GeneralMy vote of 5memberprashant_8420 Feb '13 - 22:53 
Nice explain
QuestionFTP Uploadmemberpersilvia14 Feb '13 - 7:46 
Dear Sunasara,
could you please help me to adapt the code for FTP upload?
I'm new to .net
 
Thank you
Silvia
GeneralMy vote of 3memberMember 950677012 Feb '13 - 16:47 
This is not real time. The file is uploaded to the server, and then the progress bar is initialized.
QuestionTanksmemberAtmahmoud14 Feb '13 - 9:24 
Tanks
GeneralMy vote of 5memberTejas Vaishnav10 Dec '12 - 17:29 
Excellent article.
GeneralRe: My vote of 5professionalSunasara Imdadhusen19 May '13 - 19:57 
Thanks

sunaSaRa Imdadhusen
+91 99095 44184

GeneralMy vote of 5memberMember 327776030 Nov '12 - 21:30 
excellent. thanks Imdad
GeneralMy vote of 5membergiocos200429 Nov '12 - 22:01 
clear, quickly and easy to integrate.
GeneralRe: My vote of 5professionalSunasara Imdadhusen19 May '13 - 19:58 
Your appreciations will encourage me to share my knowledge to the community

sunaSaRa Imdadhusen
+91 99095 44184

QuestionWhy does the progressbar start in a delay ?memberjudyIsk6 Nov '12 - 19:46 
Hi, thanx for the article! its great!.BUT....
when i tested locally it all looked good. once i tried on the server this is what happens.(this is noticed more with LARGE files)
the progressbar gets to 100% and says INITIALIZING Upload..., now nothing happens, seems like the file is beeing uploaded to something(????) then once thats finished(which can take awhile cuz its a large file-300mb) then the progressbar starts working nicely.
 
WHAT IS HAPPENING WHEN I CLICK UPLOAD? HOW CAN I GET THE PROGRESSBAR TO START WORKING FROM THEN?
 
THANX!
Judy
AnswerRe: Why does the progressbar start in a delay ? [modified]membermisiektg17 Nov '12 - 7:01 
This is because file is uploaded to the server first(This is, why it takes so long and depends of data you are posting. Locally can get quickly but in real environment it depends form server throughput.). Just after upload is completed, it starts writting to the fileStream. While doing this the uploadStatus object stored in session is updated. Now ajax requests to the webservice can get place and read progress from this session object. I think that this solution is not what everybody are looking for.

modified 17 Nov '12 - 13:08.

SuggestionRe: Why does the progressbar start in a delay ?memberairabyss29 Nov '12 - 3:47 
So, this doesn't show the progress of the upload. The file is uploaded first, and then you see the progress of copying the file from the Stream (which would be a temporary file of IIS) to the specified location.
 
In ASP .NET 4.0 you can actually monitor the upload progress, as you can see in this article:
 
http://vanacosmin.ro/Articles/Read/AjaxFileUpload[^]
BugSorry, but this is not upload progreess...memberDalamar816 Nov '12 - 7:24 
It is not upload progress bar. It is a progress bar of saving file byte-by-byte after real upload to IIS already complete...
GeneralMy vote of 5memberpinguit30 Oct '12 - 17:13 
Excellent
GeneralRe: My vote of 5professionalSunasara Imdadhusen19 May '13 - 19:59 
I fill encouraged

sunaSaRa Imdadhusen
+91 99095 44184

Questionlimit file sizememberrandydom5 Oct '12 - 3:32 
Hi , how to limit file upload size , i mean when the user wants to upload a file that exceeds " maxRequestLength " he will get an error message " Selected file is too big " .
 
many thanks
QuestionMultiple filesmembermanognya kota4 Oct '12 - 8:18 
Can we use this to upload multiple files in asp.net website?i.e., can we select multiple files in the file dialog box?
-Manognya
__________________________________________________
$ God gives what is best.Not what all you wish Smile | :)

GeneralMy vote of 5memberNaveen Sylvan25 Sep '12 - 19:47 
Worked like a charm! Thanks
Question[My vote of 1] This is deceptivememberWagner Kye25 Sep '12 - 5:11 
This not works at real time, this Uploads a file to server once, and the progress bar is only for server writting already uploaded file to the disk
 

thanx for trying , but is no tfunctional
GeneralMy vote of 5memberKneeland23 Sep '12 - 17:29 
Thank you, I appreciate your article so much.
QuestionGet and Save the md5 checksummemberrandydom23 Sep '12 - 5:15 
Hi, really very nice piece of code , i just wanted to add an extra feature :
 
How could i Calculate the md5 checksum of the file being uploaded and then save this MD5 value into the Database ?
 
yours,randy
Questionlong time for waitingmemberusmanrv3 Sep '12 - 21:34 
Hello, Sunasara Imdadhusen
Very very good component.
but when i try upload file about >10 MB , I need wait long time .
Progress bar goes to 100% and shows message Initializing upload ....
after few minutes shows size length and works good.
on my local machine it works very fine. Problem is only on server.
May be problem in web.config adjustment?
May you help me?
Thanks
Oleg
AnswerRe: long time for waitingmemberWagner Kye25 Sep '12 - 5:03 
I'm having the SAME problem.. looks like engine file doesn't work asynchronous
GeneralMy vote of 4membermrwsd28 Aug '12 - 1:05 
Need to fix Error with pages using masterpages
BugError with MasterPage and UserControlmembermrwsd26 Aug '12 - 18:29 
First i'd like to thank you for your greate work (: Smile | :) .
________________________________________________________
 
your control working fine in a normal forms but if i trying to move it to user control "that mean i want to create a user control hold the the code and design in the Default.aspx" it done but i got an error on Click "Upload" in the check file exists function in the java script code :
function fileExists() {
    var selectedFile = fileUpload.value.split('\\');
    var file = $get('gvNewFiles').getElementsByTagName('a');
    for (var f = 0; f < file.length; f++) {
        if (file[f].innerHTML == selectedFile[selectedFile.length - 1]) {
            return file[f].innerHTML;
        }
    }
    return '';
}
 
the "file" object return null !! i can't resolve it ?/?

Also When i use the control on form inherited from masterpage i got the same Erorr.
any one can help ?????
Mr:wsd

GeneralRe: Error with MasterPage and UserControlmemberNedgod31 Aug '12 - 2:04 
Having exactly the same problem. I've noticed that this was assked in earlier messages but not responded. Appreciate for any advice ?
AnswerRe: Error with MasterPage and UserControlmembermrwsd31 Aug '12 - 5:39 
Finlay i got an idea and it works very well with me Smile | :) Smile | :)
i but the Whole form in "iframe" in my nested page you can try this code :
 
<%@ Page Title="" Language="C#" MasterPageFile="~/Admins/design/MasterPage.master"
    AutoEventWireup="true" CodeBehind="NewsLetters.aspx.cs" Inherits="Warus.Admins.NewsLetters" %>
 
<asp:Content ID="Content6" ContentPlaceHolderID="SheetContentPlaceHolder" runat="server">
    <table class="Container" cellpadding="0" cellspacing="4" style="width: 100%; height: 100%"
        border="0">
        <tr>
            <td style="width: 100%; height: 100%">
                <iframe id="myFrame" frameborder="0" scrolling="no" src="Default.aspx">
                </iframe>
            </td>
        </tr>
    </table>
    <style type="text/css">
        #uploadFrame
        {
            height: 600px;
             width: 782px;
        }
    </style>
</asp:Content>
<asp:Content ID="Content7" runat="server" ContentPlaceHolderID="ScriptIncludePlaceHolder">
    <script type="text/javascript" src="<%= ResolveUrl("~/Admins/jquery.js") %>"></script>
    <script type="text/javascript" src="<%= ResolveUrl("~/Admins/script.js") %>"></script>
</asp:Content>
 
this a trick but i'm still trying to resolve the javascript code Hmmm | :|
Mr:wsd

GeneralRe: Error with MasterPage and UserControlmemberNedgod31 Aug '12 - 8:01 
Thank you, worked great.
GeneralRe: Error with MasterPage and UserControlmemberMember 42570261 Apr '13 - 3:06 
try
 
var file = $get('ctl00_MainContent_gvNewFiles').getElementsByTagName('a');
 
Let me know how you go
QuestionConfiguration upload files larger than 200MBmemberePrata23 Aug '12 - 12:06 
Hello Sunasara Imdadhusen,
 
Your component is very good and has met the projects I've done.
 
And I'm trying to implement a system using it, but I'm having trouble uploading files larger than 200MB.
 
Will some setting that has to change?
 
My changes:
     <httpRuntime
        executionTimeout = "3600"
        maxRequestLength = "2097151" />
 
     <security>
       <requestFiltering>
         <requestLimits maxAllowedContentLength="6048560"/>
       </ requestFiltering>
     </ security>
 
I am using framework 3.5.
 
If possible give me your email so we can talk directly.
 
Thank you and congratulations for the project.
 
My development environment:
 
Win7 - Visual Studio 2008 - ASP NET FrameWork 3.5 - IE9
AnswerRe: Configuration upload files larger than 200MBmemberdotted_decimal28 Dec '12 - 0:14 
Could you find a solution? I am facing similar problem. I am trying to upload a file of 1GB in size but am getting OutOfMemoryException with fileUpload.FileBytes.
Generalmy +5memberRajesh Biswas28 Jul '12 - 6:42 
very nice article...Thumbs Up | :thumbsup:
GeneralDifferentiate uploads based on Project IDmemberDivicraft27 Jul '12 - 2:48 
I have a Db with tables for service projects. Using filters each project's data can be viewed individually by way of Query string like /Details.aspx?ID=Proj1
How do U get to separate uploads for each project so that when admin logs into admin section access, say, Project 2(Details.aspx?ID=Proj2)? is there a way to create a separate directory for each Projects uploads or some SQL to separate the uploads for each project?
I am only a designer learning on the job doing work free for a non profit. Would like to come through for them. Help would be appreciated. Thanks
GeneralMy vote of 5membersaxenaabhi625 Jul '12 - 19:46 
this is good, and handy. my 5.
I would suggest you to integrate drop files facility available in advance browsers. like how gumtree do it.
GeneralMy vote of 5memberAbinash Bishoyi24 Jul '12 - 3:17 
Nice
QuestionGood Utility ComponentmemberSuchi Banerjee, Pune24 Jul '12 - 1:51 
Thanks for sharing.
GeneralMy vote of 5memberMember 43771123 Jul '12 - 20:34 
Gratulations! Exact what I was searching for! Thank you!
GeneralMy vote of 5memberbilal hashmi22 Jul '12 - 17:47 
Very Excellent
GeneralMy vote of 5memberAlluvialDeposit21 Jul '12 - 2:38 
Thank you! Nice article Smile | :)
GeneralMy vote of 5memberSoMad20 Jul '12 - 21:13 
Great work!
 
Soren Madsen

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 21 Jul 2012
Article Copyright 2010 by Sunasara Imdadhusen
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid