Click here to Skip to main content
Email Password   helpLost your password?
Sample Image

Back in the ASP world, uploading files via a web page was a tricky problem. The problem was that due to the encryption type of the form used to submit the file from the client's browser, receiving such files on the server side was a complex task. Data had to be retrieved as a safe byte array and decrypted before it could be used. Most of the people resorted to 3rd party DLLs. A few wrote their own DLLs and some even wrote purely ASP solutions to this problem using VBScript. Fortunately for us, the .NET Framework SDK comes with a few classes that make uploading of the files simple from the web developer point of view. This article will demonstrate following concepts:

Setting Up an HTML Form for File Uploading

The requirements for an HTML form to be able to upload files are very simple: you have to use multipart/form-data encryption and you have to use method of post.

<form id="Form1" method="post" runat="server" enctype="multipart/form-data">

HTML input control that is used to upload file has a simple type of file.

<input id="filMyFile" type="file" runat="server">

This is all that needs to be done to an HTML form for a client to be able to submit a file to your ASP.NET application.

Receiving Uploaded Files

<INPUT TYPE="file" corresponds to the System.Web.UI.HtmlControls.HtmlInputFile type of object on the server side. So if you, like myself, are using a CodeBehind architecture for your page you will have a member field definition similar to this in your class:

protected HtmlInputFile filMyFile;

HtmlInputFile classes have a few different properties, but the only one that really concerns us here is PostedFile. This property will tell us all we need to know about the file that had been uploaded to our server. The PostedFile property is null if no file was submitted by a client. So, we can simply check whether a file was sent by doing something like this:

if( filMyFile.PostedFile != null )
{
    // File was sent

}
else
{
    // No file

}

The PostedFile property will contain a valid System.Web.HttpPostedFile object if file indeed was uploaded. HttpPostedFile provides us with 4 properties:

Let's find out the size of the file:

// Get a reference to PostedFile object

HttpPostedFile myFile = filMyFile.PostedFile;

// Get size of uploaded file

int nFileLen = myFile.ContentLength;

Now that we know the size, we can move on to retrieving the data. First, we need to allocate a byte array to store the data:

// Allocate a buffer for reading of the file

byte[] myData = new byte[nFileLen];

Next, we can read the uploaded file in our buffer using the InputStream object:

// Read uploaded file from the Stream

myFile.InputStream.Read(myData, 0, nFileLen);

At this point, we have successfully retrieved the uploaded file into a byte array called myData. What to do with it next depends largely on the requirements of your application. I will show both saving the file to hard drive and to a database in the next sections.

Saving Uploaded Files to Disk

I wrote a simple function for my demo project that stores files to a disk:

// Writes file to current folder

private void WriteToFile(string strPath, ref byte[] Buffer)
{
    // Create a file

    FileStream newFile = new FileStream(strPath, FileMode.Create);

     // Write data to the file

    newFile.Write(Buffer, 0, Buffer.Length);

    // Close file

    newFile.Close();
}

I pass a full path of where I want a file to be stored and reference to a buffer with file data to this function. It uses the System.IO.FileStream object to write a buffer to a disk. This very simplistic 3 lines of code approach will work in most cases. A couple of considerations here are: getting the filename of the uploaded file and the security. Since the FileName property of PostedFile is a full path to the uploaded file on a client's computer, we will probably want to use only the filename portion of that path. Instead of using some parsing techniques to look for backslashes and things like that, we can use a very convenient little utility class: System.IO.Path.

string strFilename = Path.GetFileName(myFile.FileName);

Security is another matter. In my demo project, I store files in the same folder where the project is executed. In order for that to work, the ASPNET account (the account that is used to execute ASP.NET processes) has to have Write permissions on that folder. By default it does not, so you need to right-click the folder, go to the security tab and add the ASP.NET account to the list. Then grant write permissions to that account by checking the Write checkbox and click OK.

Saving Uploaded Files to a Database

The following function is used in my demo project to store uploaded files in the database:

// Writes file to the database

private int WriteToDB(string strName, string strType, ref byte[] Buffer)
{
    int nFileID = 0;

    // Create connection

    OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

    // Create Adapter

    OleDbDataAdapter dbAdapt = new OleDbDataAdapter("SELECT * FROM tblFile", dbConn);
            
    // We need this to get an ID back from the database

    dbAdapt.MissingSchemaAction = MissingSchemaAction.AddWithKey;
            
    // Create and initialize CommandBuilder

    OleDbCommandBuilder dbCB = new OleDbCommandBuilder(dbAdapt);

    // Open Connection

    dbConn.Open();
                    
    // New DataSet

    DataSet dbSet = new DataSet();
                    
    // Populate DataSet with data

    dbAdapt.Fill(dbSet, "tblFile");

    // Get reference to our table

    DataTable dbTable = dbSet.Tables["tblFile"];

    // Create new row

    DataRow dbRow = dbTable.NewRow();

    // Store data in the row

    dbRow["FileName"] = strName;
    dbRow["FileSize"] = Buffer.Length;
    dbRow["ContentType"] = strType;
    dbRow["FileData"] = Buffer;

    // Add row back to table

    dbTable.Rows.Add(dbRow);

    // Update data source

    dbAdapt.Update(dbSet, "tblFile");

    // Get newFileID

    if( !dbRow.IsNull("FileID") )
        nFileID = (int)dbRow["FileID"];
            
    // Close connection

    dbConn.Close();

    // Return FileID

    return nFileID;
}

The Access database that I used in the demo project has only one table tblFile that has 5 fields defined as follows:

FileID � autonumber Filename � text 255 FileSize - long integer ContentType � text 100 FileData � OLE Object

The code in the above function is very straightforward. I create OleDbConnection, OleDbDataAdapter and DataSet objects and then append a row to the only table in DataSet. The important thing to note here is that the OleDbCommandBuilder object needs to be created and initialized with a reference to the OleDbDataAdapter object to build the insert query for us automatically. Also, if you would like to retrieve the newly assigned FileID of the file you have just stored in the database, you need to make sure you set the MissingSchemaAction property of Adapter to MissingSchemaAction.AddWithKey. That assures that the Primary Key/autonumber FileID field will be populated with the new ID when you call the Update method of your DataAdapter.

The local ASP.NET account has to have Write permissions to a database file in order for your code to succeed. If your file is placed anywhere under wwwroot, you will need to manually give the database file all the necessary permissions before running my demo project.

Retrieving of a File from a Database

I used the same ASPX page to read and return file data out of the database in my demo project. I check for the FileID parameter being passed to a page. If it was passed, I know that I need to return a file rather than process the user's input:

private void Page_Load(object sender, System.EventArgs e)
{
    // Check if FileID was passed to this page as a parameter

    if( Request.QueryString["FileID"] != null )
    {
        // Get the file out of database and return it to requesting client

        ShowTheFile(Convert.ToInt32(Request.QueryString["FileID"]));
    }
            
}

The ShowTheFile function does all the work here:

// Read file out of the database and returns it to client

private void ShowTheFile(int FileID)
{
    // Define SQL select statement

    string SQL = "SELECT FileSize, FileData, ContentType FROM tblFile WHERE FileID = " 
                + FileID.ToString();

    // Create Connection object

    OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

    // Create Command Object

    OleDbCommand dbComm = new OleDbCommand(SQL, dbConn);

    // Open Connection

    dbConn.Open();

    // Execute command and receive DataReader

    OleDbDataReader dbRead = dbComm.ExecuteReader();

    // Read row

    dbRead.Read();

    // Clear Response buffer

    Response.Clear();

    // Set ContentType to the ContentType of our file

    Response.ContentType = (string)dbRead["ContentType"];

    // Write data out of database into Output Stream

    Response.OutputStream.Write((byte[])dbRead["FileData"], 0, (int)dbRead["FileSize"]);

    // Close database connection

    dbConn.Close();

    // End the page

    Response.End();
}

I am using OleDbConnection, OleDbCommand and OleDbDataReader objects to retrieve data. The next step is to clear the Response output buffer to make sure that no other information is being sent to the client besides our file data. That will only work if buffering of your pages is turned on (default in ASP.NET). I set the ContentType property of the Response object to the content type of our file. Then I write file data into the Output stream of the Response object. The important thing here is to call Response.End() at the end to prevent farther processing of this page. We are done here and we do not want for other code to execute.

Security Considerations

Important:

Because my demo project writes files to disk or data to an Access database, you need to make sure that security permissions are set properly on folders and files where you want to write. Beta versions of .NET used the System account to execute ASP.NET processes and it had access to everything on your computer. However, the final release of .NET runs all ASP.NET processes under a local ASP.NET account. That account needs to have Write permissions to all the folders and files that are being used to write data.

In order to make my demo project work under the .NET release version, you need to place it in a folder (anywhere under wwwroot) and set the permissions of that folder as follows: Right-Click the folder, go to Properties, Security tab, make sure the local ASPNET account has Read and Write permissions on that folder. If not, Add local ASPNET account to the list and give it read and write permissions. Click OK.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralMy vote of 1
amitsinh parmar
21:02 29 Oct '09  
aaaa
GeneralMy vote of 1
sumeetkumar123
23:18 27 Aug '09  
idiot
GeneralAdd a progress bar and reduce memory usage
Chris Hynes
9:37 18 Jun '09  
This sample is good for what it does, but it doesn't have a progress bar and shows loading files into memory which could kill a server

If you want more check out SlickUpload, my ASP.NET upload control. It has an AJAX progress bar, handles files up to 4 GB, doesn't load files into memory when uploading into a database, and supports ASP.NET AJAX (working in an UpdatePanel), and ASP.NET MVC.

If you're using this for personal non-commercial use, we have a free license offer with linkback!


GeneralMobile File Upload
AmmarHaider
21:21 18 Mar '09  
Is it possible to upload files from mobile device. using mobile web forms.?
Generalexample of upload and enumerate ZIP file
Cheeso
16:16 12 Feb '09  
Get the source at:
http://dinoch.dyndns.org:6060/zip/DotNetZip-Example-Csharp.aspx[^]
Generalanothe optiopn: http://www.mo8.co.il/WebControls.aspx
hitthelink
0:49 30 Dec '08  
"http://www.mo8.co.il"
Questionhow to do a confirmation page in c#
efah
23:59 22 Oct '08  
hi,
i'm new to this .net...
i've set up a web application which requires user to register using c#...
so, i do not know how to do a confirmation page after user fill in all the required values in the first registration page....

do anyone know how to do this?

pls help me...
thanks in advance!!!

~ifah~

GeneralPlease, put sample that works or give up your work...
Member 308179
9:46 22 Oct '08  
It's not working dude...
Generalplease help me!
nhanksd85
9:20 4 Oct '08  
When we want to upload a file, we must click on Browse button or type the path of the upload file. Now, in my web application, I always upload a file to server, so I want set the path on the code, someone can tell me what should I do, thanks alot. The property Value of HtmlPostedFile is readonly, i don't know what to do!
GeneralRe: please help me!
Chris Hynes
9:32 18 Jun '09  
You can't select a file through code -- that would be a huge security hole. The user must actually manually select the file every time.


GeneralVisit for Buffered File Donwload
mayurmv
23:56 26 Sep '08  
http://developmentzone.blogspot.com/2008/09/buffered-file-download-from-aspnet-web.html[^]
GeneralFileUpload Control is getting Refreshed on Page refresh
mrMdpendable
21:41 23 Sep '08  
Hi,

I have an application which will upload files to the server,i used fileupload control and on clicking send iam checking that selected file formats,if it is not an image file then iam displaysing a message to select a image file but the selected file is getting refreshed on displaying message from the control,

How can i keep selected file to be there in fileupload control even after browser refresh/displaying message.

Please reply me asap.

Thanks in Advance..
Vijay
Questionhelp
sai12345
11:21 23 Aug '08  
iam doing project in web application so wh my prob is iam trying to do a login page but i got error on login authentication ,so wt is it please help me or provide total code for that.
GeneralGood work..
Member 2097719
1:57 14 Aug '08  
Really a good work done..and so simple to understand..thanks a lot.. Smile
GeneralSimple and Easiest Explanation
DotNetGuts
18:33 6 Aug '08  
Good Job, Simple and Easiest Explanation.

Keep going good work Smile
DotNetGuts (DNG)Cool
http://dotnetguts.blogspot.com

DotNetGuts
"Lets Make Programming Easy"

Logon to www.DotNetGuts.2ya.com
Join Us @ DotNetGuts@YahooGroups.com

Generalfile upload with asp.net by get method
umeshdaiya
21:38 10 Jul '08  
if(filMyFile.PostedFile!=null)
{
// File was sent
HttpPostedFile myFile = filMyFile.PostedFile;
int nFileLen = myFile.ContentLength;
byte[] myData = new byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);
FileStream newFile = new FileStream("c:\\", FileMode.Create);
newFile.Write(Buffer, 0, Buffer.Length);
newFile.Close();
}


code as i written here
problem is that i am receiving file from client side
client send me mime type file and now i would like to know that is a .jpg file or .png file or other image format file and now i want to store in harddrive how i convert this file and store in harddrive please help me.
QuestionHow to check whether the uploaded document is password protected
parvathy_ramachandran
19:17 4 Jun '08  
I am doing file upload using Visual Studio 2005(ASP.NET)
I am uploading a word document and saving it in the database.
And know stuck with some issues.
I do not know how to check whether the uploading file is password protected.
I am really hoping for great help from all the experts or knowledgeable on this.I am hoping for a step by step explanation as I am totally new in this fields.All help are highly aprreciated.

Thanks.
GeneralError after publishing the web site
swapna_samala
2:57 28 May '08  
Hi All,

I've created a sample website and published it. I tested the site before publishing and is working fine. But when I tried to access the site after publishing it throwed the error as...

A name was started with an invalid character. Error processing resource 'http://localhost/TEST/Default2.aspx'. Line 1, Pos...

<%@ page language="C#" autoeventwireup="true" inherits="Default2, App_Web_4q-v0xxu" %>
-^

But there are no such errors in that page.

Please help me out from this..

Thanks in advance,
Swapna
GeneralC#
Member 4720591
1:08 12 Mar '08  
How To Receive a data from remote system using c#

Manoj

GeneralAnyone interested in ASP.NET file upload might want to check http://www.codeplex.com/VelodocXP
Jacqou
6:32 24 Nov '07  
This is a great article and certainly an interesting alternative to the open-source Velodoc ASP.NET module and server controls which I have been using.

The source code of the Velodoc VS solution is available for download at http://www.codeplex.com/VelodocXP.

The sample application can be tried online at http://www.velodoc.net and more information can be found at http://www.velodoc.com.

Congratulations for this excellent article!


General: Missing partial modifier on declaration of type 'FileUpload.WebForm1'; [modified]
Davidletterman
15:31 26 Oct '07  
does anyone know how to fix this error


vs wants a partial class not a public class for some reason but as when i change it i get another error

'FileUpload.WebForm1' already contains a definition for 'filMyFile'

can someone help me with this
GeneralRe: : Missing partial modifier on declaration of type 'FileUpload.WebForm1';
feziko
2:56 14 Jan '08  
I have the same problem.Frown
can anyone help me with this. Please? Big Grin
GeneralRe: : Missing partial modifier on declaration of type 'FileUpload.WebForm1';
Jimmy_Le
7:28 26 Aug '09  
You just change "FileUpload" -> "FileUpload1" .it is ok

Jimmy Le

AnswerRe: : Missing partial modifier on declaration of type 'FileUpload.WebForm1';
clayroad
23:27 18 Feb '08  
Just leave out this line:
protected HtmlInputFile filMyFile;

Found the answer here: http://forums.asp.net/t/985837.aspx
GeneralRe: : Missing partial modifier on declaration of type 'FileUpload.WebForm1';
Thi
9:20 11 Mar '08  
Error 1 The type name 'WebForm1' does not exist in the type 'System.Web.UI.WebControls.FileUpload' c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\new folder\d2c8e119\11fe62d7\App_Web_myemihgz.0.cs 121
hic i don't repair this


Last Updated 23 Jan 2002 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010