[How Do I:] Multiple File Uploads in ASP.NET 2

Please install Silverlight or click download to watch video locally.

In this video I will demonstrate uploading a dynamically determined number of files to your ASP.NET application.

Presented by Joe Stagner

Duration: 16 minutes, 9 seconds

Date: 12 February 2008

Watch    Video   |   Download    Video   |   VB Code    C# Code

Video downloads: WMV  |  Zune  |  iPod  |  PSP  |  MPEG-4  |  3GP

Audio downloads: AAC  |  WMA  |  MPEG-4  |  MPEG-3  |  MPEG-2

Comments : 64

Leave a Comment

krishnaprasadaccot@gmail.com : On March 06, 2008 2:18 PM said:

In this video when you list the uploaded images, in uploaded folder, Only the name of the files are different,but the images looking identical . Is that a problem with my browser, or you skipped that one?

sagesmith : On March 11, 2008 12:28 PM said:

Interesting, however I fail to see any ASP.NET 2 specific innovation.  When I saw the title I thought for a minute the IE browser's common file dialog was going to support multiple file selections.  Now that would be video worthy!  It would really be a powerful enhancement and a huge step forward for browser-based applications.  I'm sure this will be a much appreciated feature for Internet sites which take a long time to upload individual files.  However for Intranet sites where the actual posting of files is quick the differences between hitting an upload button five times versus requesting 4 additional inputs then hitting an upload button is hardly worth the effort.  The frustration exits because the OS version of the common file dialog (multiple file selection, file type filtering at the dialog level, etc.) is much more robust than the browsers.

pradeepkr : On March 13, 2008 12:22 PM said:

There's an error in the C# code available for download at line 31. There's no variable named 'file', instead it should be 'uploads[i]' in place of 'file'.

JoeStagner : On March 15, 2008 12:45 PM said:

sagesmith - It's not new magic. Jst a series of techniques that developers can use.

pradeep - I know about the code error and the file is being updated. Thanks

ericdow : On March 24, 2008 1:16 PM said:

I think a tutorial on how to do multiple uploads to a database would be a good idea.

ericdow : On March 24, 2008 1:19 PM said:

Sorry there is a tutorial on doing this site.

daddyqbob50 : On March 29, 2008 4:21 PM said:

Joe

I want to upload all files from a certain client-side folder. I do not want the user to have to data enter the file names as there could be many small files. Is there any way to do this via ASP.Net? In other words how do I populate the HttpContext.Current.Request.Files collection using client script?

I have asked several ASP.Net "gurus" abou this and they do not think it is possible due to browser security restrictions. Yet the upload control does it just fine.

Thanks

Talib_dotnet : On April 03, 2008 7:01 AM said:

Hi  Joe,

Awesome video .. You  rock...

One thing  i  wanted to know is that  ..can we develop the same with ASP.NET's  FileUpload  Control    instead of HTMLFile Control....

Waiting for your reply..

Thanks..

aguila1976 : On April 24, 2008 9:09 AM said:

This code doesn´t seem to work with c# in VS2008. It works uploading one file, but not several at one time.

I did as pradeepkr and changed 'uploads[i]' in place of 'file'.

I do get some strange warning, in the end of the behind code:

catch(Exception Exp)

           {

               Span1.InnerHtml = "Upload(s) FAILED.";

           }

"The variable 'Exp' is declared but never used"

Anyone else tried it in VS2008 with c#?

mak101 : On April 25, 2008 4:29 AM said:

It's great !

However, if I just want to upload all files from a certain client-side folder, is there a video to show it?

TheDecline02 : On May 07, 2008 11:03 AM said:

This code dosen't actually work...

1. You are trying to assign HttpPostedFile to a varible called file which dosen't even exist.

2. You are only changing the filename of the saved file and not the actual file itself. So you are only uploading one file multiple times.

3. You are using Visual Studio 2008 which is .NET 3.5 and the video is labeled as ASP.NET 2.

Therefore this video is useless.

dtcs1 : On May 20, 2008 6:44 PM said:

I have tried the C# code and it does NOT WORK!

aftab : On May 24, 2008 12:07 PM said:

Thanks for this video

shweko : On June 01, 2008 7:47 PM said:

The way you called javaScript function is beautiful.

zhngmm : On June 04, 2008 5:12 PM said:

works good on me, thank you very much

dw.egun : On June 05, 2008 4:52 AM said:

Thanks for the videos. It's awesome dude......

pakpatel : On June 22, 2008 12:28 AM said:

Hi, JoeStagner

C# Program not working.So can you fix that error on buttion click event.

-Thanks

pakpatel : On June 22, 2008 12:29 AM said:

Hi, JoeStagner

C# Program not working.So can you fix that error on buttion click event.

-Thanks

pakpatel : On June 22, 2008 12:29 AM said:

hi JoeStagner

C# Program not working.So can you fix that error on buttion click event.

-Thanks

abhishek0410 : On July 02, 2008 1:43 PM said:

I want to upload all files from a certain client-side folder. I do not want the user to have to data enter the file names as there could be many small files. Is there any way to do this via ASP.Net?

or

i wan to select multiple image at once....can u tell me another way.....if i hav folder which contains images......n i browse the folder and see the all the images of that folder in thumbanil in another form and then select multiple images or select all images(like we do while selecting or deleting files on harddisk) from that form and then insert into database???? is this possible??????

cv_vikram : On August 09, 2008 8:33 AM said:

thanks....

sobriquet : On August 13, 2008 9:25 AM said:

Dear Joe,

Great Job but i am facing a problem.

I am inserting these uploaded files in a database,

and whenever i upload multiple files,i get all the different file names, but the picture or file itself is the same.

can you give me any tips??

muhammed : On August 14, 2008 6:46 AM said:

any one help me upload files and save then to sql server

ultravi0let : On August 14, 2008 12:53 PM said:

Hello,

I followed part 1 and 2, great job! :)

I'm trying to add a validation for the file type. I added this code on  btnSubmit_Click:

string FileExtention = System.IO.Path.GetExtension(upload.FileName);

if (FileExtention != ".jpg")

{

   lblMessage.Text = "only .jpg files";

   return;

}

I'm on the case when the user selects many files.

The thing is, when the user gets the message "only .jpg files", input controls are blank and the user has to select all the files all over again..

How do I keep the values on the input controls, so that the users corrects only the wrong selection(s)?

Thanks in advance.

Regards,

Sanaa RAMZI

ccoe1 : On September 08, 2008 4:19 AM said:

Great Post, works like a charm. I was wondering how to adjust the javascript to have a remove button next to the upload field to remove those created uploadfields if desired.

Thanks heaps,

Chris

varundev4u : On September 13, 2008 2:21 AM said:

Great video.....

someguy198650 : On September 17, 2008 12:51 AM said:

@ultravi0let

did you already solve ur problem, im having the same requirement.

can u please post your solution if any?

ellmo : On September 22, 2008 5:51 AM said:

Using C# code under mvs2008:

Compiler does not like the

HttpPostedFile upload = file;

line, which quite obviously should be changed to

HttpPostedFile upload = uploads[i];

works for me.

ahjeck : On September 27, 2008 5:26 AM said:

In the C# code, it appears that the original <input> box is missing a 'name' attribute. Without this attribute, it doesn't seem to count the number of files correctly...at least for me.

mengjun599242482 : On October 07, 2008 8:56 PM said:

It's very useful to me.

Thanks!

finestkatch4u : On October 28, 2008 5:55 AM said:

I guess there is a little problem.

every file is uploaded twice, but we don't note it as the second file overwrites the first one.

you can see it if you display the confirmation message for every upload using a loop or make an entry in database.

for each file there two entries in database.

Please someone correct it.

djibril_chimere_DIAW : On October 29, 2008 9:54 AM said:

Thanks ! Jërëjëf !

funluckykitty : On November 20, 2008 4:40 PM said:

The vb cod for this ROCKS!  Copied it into my site and had it working in the matter of seconds.   I went ahead and added a "sub directory" based upon a form field value.  This way all the uploads aren't dumped into the same folder.  

funluckykitty : On November 21, 2008 10:25 AM said:

I ran into a problem when I decided to add the GUID to the file name to ensure unique file names.  With the GUID, I have the same problem finestkatch4u mentions above... every file is uploaded twice.  ARGH..

funluckykitty : On November 21, 2008 3:32 PM said:

Forgot to mention, that when I try to insert the record into my database, it also inserts that value twice.  Any idea if this code will be fixed?  I hate the thought of using single file upload.  

aslesh : On December 03, 2008 4:53 PM said:

Hey how can we do the same thing using asp.net file upload control.. is it possble?

if yes, how can we ?

i am going for asp.net file upload control because if we use  html file upload we are not able to retrieve the full path of the uploaded file..

can any one help with me..

alienmoose : On December 04, 2008 9:05 PM said:

Hi Joe,

Are there any videos that shows how to compress jpg photo images dynamically while creating thumbnails to reduce the file size??  These days everyone is uploading 4Mb+ size images and it's nuts...  Dude, it would be so cool if you can show it in VB.  Thanks in advance.

htl : On December 30, 2008 5:57 AM said:

hi

here is anothe greate file upload control

full custome look !!!

www.mo8.co.il/WebControls.aspx

iperez_genius : On January 05, 2009 12:15 AM said:

I have tried the original C# code and like everybody else i am having problems with line 31.

ellmo posted that you change file to uploads(i)

but that give me an error to...

can someone enlighten me here as to why this is happening.

Ilan

iperez_genius : On January 05, 2009 12:23 AM said:

scratch that uploads[i] is the syntax...thinking...idiot!!!

briankays : On January 27, 2009 1:59 PM said:

Just trying to learn if there is a "proper" way of doing certain things or if it is just personal preference, but is there any particular reason for using the span tags instead of using a Label and setting the text content on the server that way? It may be my ignorance, but I was thinking the Label was meant to replace the span.. Thanks in advance, always looking to learn more from you guys.

GraceWink : On January 29, 2009 3:11 AM said:

Try removing

OnClick="btnSubmit_Click" in

<asp:Button ID="btnSubmit" runat="server" Text="Upload Now" OnClick="btnSubmit_Click" />

Now code only runs once, not twice.

But why can I only upload 3 files? Is there a limit as to how many it can handle? When I try more than 3 the page wont load.

GraceWink : On January 29, 2009 4:07 AM said:

Try removing

OnClick="btnSubmit_Click" in

<asp:Button ID="btnSubmit" runat="server" Text="Upload Now" OnClick="btnSubmit_Click" />

Now code only runs once, not twice.

But why can I only upload 3 files? Is there a limit as to how many it can handle? When I try more than 3 the page wont load.

GraceWink : On January 29, 2009 4:08 AM said:

It was the file size. Too big. Changed it in web.config

<system.web>

   <httpRuntime

      maxRequestLength="11000"

     />

bohunt : On February 13, 2009 3:33 PM said:

Very useful!

lonergt : On February 19, 2009 2:39 PM said:

Interesting video, but isn't there a way to do multiple file selection from the same location, instead of dynamically creating a new file upload control each time? It seems to be to be a very ineffective way to upload files

Marcilio Jr : On February 20, 2009 9:30 AM said:

Hi folks

Im trying to use this  vb code inside an UserControl in a asp.net 2.0 website using vs2k5, i inserted the code inside an updatepanel, the inputs are created and shown correctly at runtime, but when i submit form, the HttpsContext.Current.Request.Files file count is 0.

May this be an issue with the asynchpostback of the updatepanel or am i missing something?

TRU : On April 03, 2009 4:34 AM said:

hello Joe.. thanks for the great video and files.

In your .vb file you have the path to the upload folder.

How can I have user choose where they would like to upload the files. I would like the user to choose from probably a dropdown menu the folder they would like to upload to. My immediate need would be to have the user choose from about 30 different folders so they can upload to their desired folders.

Can anybody share how this could be accomplished?

Thanks,

TRU

drini83 : On April 05, 2009 11:48 AM said:

first of all thank for the video.

there is a problem in the C# source code and it hasn't been solved for a full year. apparently it looks like that the HTML file input does not take any file at all because when i put breaks points into the code the count of the "HttpFileCollection" variable still remains =0 and program does not even get into the for loop

pbali : On May 25, 2009 2:54 AM said:

hi joe

can you please help me as I want to upload large (100 MB) files to my server , and wanted to know how can i break it into chuncks and then put it togeather on the server to enable fast upload. does anybody have a example or code snippet for this

kindly share , here is what i am doing currently and it is taking a lot of time :

i have used Asp.net control which first copy the file to the server from where my service pick the file and encode it with the following method

public EncoderResult Encode(Video video)

{

string workingDirectory = new System.IO.FileInfo(video.RawStorageLocation).DirectoryName;

// Get the working file and directories

objCommon.VideoLog(video.VideoId, "Begin encoding process.");

string exeEncoder = "Encoder.exe";

string tmpjobFile = Path.GetTempFileName();

string tmpDir = GetTmpDir(video.VideoId);

objCommon.VideoLog(video.VideoId, String.Format("Temp file used during encoding \"{0}\"", tmpjobFile));

objCommon.VideoLog(video.VideoId, String.Format("Output directory for encoding results \"{0}\"", tmpDir));

// -- Create local dir to encode

if (!Directory.Exists(tmpDir))

Directory.CreateDirectory(tmpDir);

// -- Loading My Template job file

XmlSerializer xs = new XmlSerializer(typeof(JobFile));

JobFile jobfile = null;

using (Stream configStream = File.OpenRead(System.IO.Path.Combine(workingDirectory, "JobFile.xml")))

{

jobfile = (JobFile)xs.Deserialize(configStream);

jobfile.Job[0].OutputDirectory = tmpDir;

jobfile.Job[0].MediaFiles[0].Source = video.RawStorageLocation;

}

using (Stream configStream = File.OpenWrite(tmpjobFile))

{

xs.Serialize(configStream, jobfile);

}

video.Status = Convert.ToString(VideoStatus.Encoding);

objCommon.UpdateVideostatus(Convert.ToInt64(video.VideoId),"","","", video.Status);

objCommon.VideoLog(video.VideoId, "Encoding...");

// -- Create process start info

ProcessStartInfo psi = new ProcessStartInfo(exeEncoder);

psi.Arguments = "/JobFile \"" + tmpjobFile + "\"" + " /Log On";

psi.WorkingDirectory = ConfigurationSettings.AppSettings["MediaEncoderPath"];

//Hide MediaEncoder process window

psi.WindowStyle = ProcessWindowStyle.Hidden;

Process p = Process.Start(psi);

p.WaitForExit();

//video.Status = VideoStatus.Encoded;

//VideoBO.Update(video);

//VideoLogBO.Log(video, "Encode Complete.");

System.IO.FileInfo fileInfo = new System.IO.FileInfo(video.RawStorageLocation);

string videoPath = Path.ChangeExtension(Path.Combine(tmpDir, fileInfo.Name), ".wmv");

string thumbPath = Path.ChangeExtension(videoPath, null) + "_Thumb.jpg";

return new EncoderResult() { VideoFilePath = videoPath, ThumbFilePath = thumbPath };

}

Then it host it to the silverlight server with the follwing fucntion :

public Video AddMedia(string mediaFilePath, Video video)

{

//VideoLogBO.Log(video, "Begin Upload to Silverlight Streaming.");

objCommon.VideoLog(video.VideoId, "Begin Upload to Silverlight Streaming.");

video.Status = Convert.ToString(VideoStatus.Uploading);

objCommon.UpdateVideostatus(Convert.ToInt64(video.VideoId),"","","", video.Status);

//VideoBO.Update(video);

//Create zip file

string zipFilename = mediaFilePath + ".zip";

zipFilename = CreateSilverlightPackage(video, mediaFilePath);

//event1.WriteEntry("zipFilename" + zipFilename, EventLogEntryType.Information);

string filename = new System.IO.FileInfo(mediaFilePath).Name;

//event1.WriteEntry("Filename" + filename, EventLogEntryType.Information);

// Upload to Silverlight Streaming

objCommon.VideoLog(video.VideoId, "Uploading to Silverlight Streaming...");

//VideoLogBO.Log(video, "Uploading to Silverlight Streaming...");

string filesetName = Guid.NewGuid().ToString().Replace("-", string.Empty);

Uri silverlightStreamingUri = new Uri(string.Format("http://silverlight.services.live.com/{0}/{1}", ACCOUNTID, filesetName));

System.Net.HttpWebRequest request = System.Net.WebRequest.Create(silverlightStreamingUri) as HttpWebRequest;

request.Timeout = 20 * 60 * 1000;

request.ReadWriteTimeout = 20 * 60 * 1000;

//Note: Can't set authorization header with NetworkCredential or larger files time out

//request.Credentials = new NetworkCredential(ACCOUNTID, KEY);

byte[] userPass = System.Text.Encoding.Default.GetBytes(ACCOUNTID + ":" + KEY);

string basic = "Basic " + Convert.ToBase64String(userPass);

request.Headers["Authorization"] = basic;

request.PreAuthenticate = true;

request.ContentType = System.Net.Mime.MediaTypeNames.Application.Zip;

request.Method = WebRequestMethods.Http.Post;

using (System.IO.FileStream inputStream = new System.IO.FileStream(zipFilename, FileMode.Open))

{

using (System.IO.Stream requestStream = request.GetRequestStream())

{

CopyStream(inputStream, requestStream);

requestStream.Close();

}

}

which is very lengthy and time consuming process.

if any idea how to do that any suggestion should be apperciated please help me

pawan bali

filmjamr.com

feiyim : On May 28, 2009 1:40 PM said:

Man, this's awsone. ASP.NET gimmi more

pbali : On May 29, 2009 3:52 AM said:

hey guys is there anybody who can help me?

nojava4u : On July 28, 2009 4:17 PM said:

Great videos Joe...I love them and have viewed almost all of them. I have been looking to use this Multi-File upload but I need my text/csv files loaded/read into my MSSQL database table. How do I read the csv file into the database?

nojava4u : On July 28, 2009 4:42 PM said:

or How can I change the path so it uploads to my /app_data folder? I tried variations of /app_data// //app_data/ etc. Any help would be appreciated.

xcomms : On August 18, 2009 11:00 AM said:

As already commented above, to make the c# code work, you need to change line 31 to read:

HttpPostedFile upload = uploads[i];

This will point to the correct file in the uploads array for the current iteration.

If you are adopting this code for yourself and are not getting any images into the Request.Files collection, make sure that your first input on the page contains a runat="server" attribute. Without that, the Request will not contain the file collection and you will not be able to iterate through the uploads array.

stanly : On August 22, 2009 8:37 AM said:

its not working...

stanly : On August 22, 2009 8:38 AM said:

Sorry guys.... its working fine

stanly : On August 22, 2009 9:17 AM said:

Hi guys... its working... i want to limit the number of file upload control... any idea? please

stanly : On August 22, 2009 9:19 AM said:

its working fine

stanly : On August 22, 2009 9:36 AM said:

How to limit number of file upload control.... anybody?

MasterV23 : On November 17, 2009 4:10 PM said:

How can you apply this to 2 different sets of upload locations on the same page?

I know the HttpFileCollection Uploads = HttpContext.Current.Request.Files;

Will get the current files from the fileupload boxes. But I have two seperate uploads that go to different locations.

vamsi2 : On November 24, 2009 2:42 AM said:

Hey -

I am having the same problem as some of the others on this page. Although I choose multiple files, it is still uploading the same file but different file names.

Anyone able to get past that problem yet?

vamsi2 : On November 25, 2009 12:37 AM said:

Ok. I got it finally. It was not that tough. If you want to avoid the time I spent on this, make the following changes to joe code:

1. Change the 'fileField' to 'fileField0' in the aspx page

2. Change the start index to 1 instead of 100

3. In the vb file, declare a new filefield attribute (fileFieldName)

4. Set the 'ID' of the filefield to "fileField" + i.ToString()

5. Change 'fileField' everywhere in the .net code file to 'fileFieldName'

That was it. Note that I did this in VB. I believe the same changes can be applied to C#

silu44 : On November 25, 2009 10:44 AM said:

Please any one help me ! i want to make a page to upload video into folder form a form ,

adding title , date , place , File, image

any help will be appreciated

Leave a Comment

You must be logged in to leave a comment. Click here to log in.

Microsoft Communities