jump to navigation

Using the FileUpload web server control in your asp.net website November 22, 2008

Posted by fofo in .NET, asp.net 2.0, C#, Visual Studio 2005, Visual Studio 2008.
Tags: , ,
trackback

In this post i would like to talk about another web server control, FileUpload, which was a control included in  the ASP.Net 2.0 framework. I will try to demonstrate,as always with an example, how to upload one file and how to upload multiple files using the FileUpload control. Basically with this control you try to give the user the same functionailty with a ftp client.

For more information on this control have a look at the msdn reference, here

If you remember back in the days of ASP.NET 1.0 and ASP.NET 1.1 we had to use  the HTML FileUpload server control. This control put an <input type="file"> element on your Web page to enable the end user to upload files to the server. To make this work however, we had to add, enctype="multipart/form-data" to the page’s <form> element.

Let’s start a new project to demonstrate out example

1) Launch Visual Studio 2005/2008

2) Create a new asp.net web application in C#

3) Call it “uploadcontrol”

4) Drag and drop in the default.aspx page a FileUpload control from the Toolbox

5) If you run your application now , you will see a page that does not do much, just a textbox and “Browse” button that are part of the FileUpload control

6) Stop your application and place a button in the default.aspx page

7) Add a Label control in your application. Leave the default names for all the controls on the page.

8) Create a folder in the C drive and call it “myUploads”

9) Double click on the button and in the event handling routine and type

if (FileUpload1.HasFile) {
FileUpload1.SaveAs(“C:\\myUploads\\” + FileUpload1.FileName);
Label1.Text = “File name: ” +
FileUpload1.PostedFile.FileName + “<br>” +
FileUpload1.PostedFile.ContentLength + ” kb<br>” +
“Content type: ” +
FileUpload1.PostedFile.ContentType;
}
else
{
Label1.Text = “You have not selected a file or the file has not been found.”;
}

First of all let’s explain the lines above.

Initially we use the HasFile Property which returns a value indicating whether the FileUpload control contains a file.

10) Run your application again and try to upload a file

If that is true we append in the text property of the Label control , the following information

  • filename
  • file size
  • type of the document, e.g image,word document, e.t.c

We achieve that by using the PostedFile property , which holds the file that is being uploaded.

Before going to show more things regarding the FileUpload control, i will add a Try Catch statement in the code above to provide some sort of exception handling.

if (FileUpload1.HasFile)
try
{
FileUpload1.SaveAs(“C:\\myUploads\\” + FileUpload1.FileName);
Label1.Text = “File name: ” +
FileUpload1.PostedFile.FileName + “<br>” +
FileUpload1.PostedFile.ContentLength + ” kb<br>” +
“Content type: ” +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = “ERROR: ” + ex.Message.ToString();
}
else
{
Label1.Text = “You have not specified a file or the file has not been found.”;
}

Now let’s see how you can upload mutliple files from a single page.

1) Create a new .aspx page and add it to your project, by adding a new item from the Solutions window.

2) Place 3 FileUpload controls on the page. Also add a button and a label control.

3) double click on the button

4) In the event handling routine for the click event of the button, type

thefileupload(FileUpload1);
thefileupload(FileUpload2);
thefileupload(FileUpload3);

In order to upload the three files at once, I make 3 seperate calls to the method , thefileupload.

So I have created a method of my own which I call thefileupload. This is the code for the method

private void thefileupload(FileUpload upload)

{
if (upload.HasFile)
try
{
upload.SaveAs(“C:\\myUploads\\” + upload.FileName);

}
catch (Exception ex)
{
Label1.Text = “ERROR: ” + ex.Message.ToString();
}
else
{
Label1.Text = “You have not specified a file or the file has not been found.”;
}
}

There is nothing fancy about this code. It is exactly the same as the previous bits. I just placed this code inside a method.

If you want the file upload functionality to work make sure that the destination folder on the server is  writable for the account used by ASP.NET. If ASP.NET is not enabled to write to the folder you want, you can enable it using the folder’s properties. If you want to permit your users to upload large files you should overwrite in the web.config file, the default size limitation which is 4MB (4096kb)

Hope it helps.

If you want the source code you can email me.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Comments»

1. DotNetURL - November 27, 2008

Hi,

Nice blog..publish you new content url at http://www.dotneturl.com and get reader and back link form us for free.

2. Kumar - December 1, 2008

hey Thanks for your blog. I am trying to upload a fiel to a http://ftp.. how can i do this ?

3. Anand - December 3, 2008

this is a nice post for the beginners..
the way of presenting the idea is good

4. ravi kumar Singh - December 15, 2008

Hi this article is useful for me, but I want that as soon as I select the file, the I should be able to display the properties of the selected file in the text boxes before uploading the file.

5. Paresh - July 13, 2009

Hi There,

Defenitely a Useful Article for me, since I need to set up something similar to this, where the End-User is allowed to Upload and Download Documents, either from a remote Server or their own PC’s.

My Question is can I somehow Load the Links to these documents in some Drop-Down Box on my Web Page.

Your Help would be greatly Appreciated.

Regards Paresh

6. Arunkumar - April 19, 2011

please slove this problem for me my code is here
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
con=new SqlConnection(“Data Source=COMPAQ\\SQLEXPRESS;Initial Catalog=imgupload;Integrated Security=True”);
con.Open();

}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string spath;
spath = Server.MapPath(“~/”);
string pho, na;
na = TextBox1.Text;
pho = FileUpload1.HasFile;
if (FileUpload1.HasFile)
{
string str = “insert into pho2 values(‘” + na + “‘,'” + pho + “‘)”;
cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
FileUpload1.SaveAs(spath + pho);
Label3.Text = “Record Added”;
TextBox1.Text = “”;
}
else
{
Label3.Text = “Select a Photo”;
}
}
catch (Exception e1)
{
Label3.Text = “ERROR” + e1.Message;
}
}
}

if i compile this code means
“Error 1 Cannot implicitly convert type ‘bool’ to ‘string’ E:\Phoupload\Default.aspx.cs 30 19 E:\Phoupload\ “

7. vema - July 11, 2011

Please solve this problem

i have done design in html i want upload file through this code
i had given

protected void Page_Load(Object Sender, EventArgs e) {
MailMessage objEmail = new MailMessage();
objEmail.To = “vemareddy2005@gmail.com”;
objEmail.From = “vema.876@gmail.com”;
objEmail.Subject = “interview”;
objEmail.Body = “you have an interview”

objEmail.BodyFormat = MailFormat.Html;
objEmail.Priority = MailPriority.High;

string filename =Request.Form[“FileAtt”];
FileAtt.SaveAs(Server.MapPath(“~/”)+filename);

try{
SmtpMail.Send(objEmail);
Response.Write(“Your Details are sent sucessfully”);
Response.AddHeader(“REFRESH”, “10;URL=http://www.sgindiaprojects.com”);
}
catch (Exception exc){
Response.Write(“Send failure: ” + exc.ToString());
}
}

submission Career Details


Leave a comment