Introduction
In this article I have explained how to upload multiple files using file upload control. I have used jQuery plugin for uploading multiple files.
I have also explained how to check for file type, file maximum size limit using jQuery & also using server side validation code.
Download the Following Files
Namespace used
using System.Security.Cryptography; using System.Text; using System.IO;
Step 1: Include the jQuery Files needed on the page.
Assuming you have downloaded these files, create a reference to these files in the <head> section of your page as shown below:
<head id="Head1" runat="server"> <title>Multiple File Upload using JQuery</title> <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script> <script src="Scripts/jquery.MultiFile.js" type="text/javascript"> </script> </head>
Step 2: Add File Upload Control & Button on the Page.
<asp:FileUpload ID="FileUpload1" runat="server" class="multi" accept="gif|jpeg|bmp|png|jpg" maxlength="5" /> <br /> <asp:Button ID="btnUpload" runat="server" Text="Upload All" OnClick="btnUpload_Click" /> <br /> <asp:Label ID="lblMsg" runat="server" Text="">\ </asp:Label>
Step 3: Double click on Upload Button & Write the code that is used to upload files.
protected void btnUpload_Click(object sender, EventArgs e) { if (ServerSideValidation() == true) { string SavePath, Msg = null; // Get the HttpFileCollection HttpFileCollection hfc = Request.Files; for (int i = 0; i < hfc.Count; i++) { HttpPostedFile hpf = hfc[i]; if (hpf.ContentLength > 0) { SavePath = ConfigurationManager.AppSettings["PatientPhotoImages"].ToString() + GetUniqueKey() + GetFileExtension(hpf.FileName); hpf.SaveAs(Server.MapPath(SavePath)); //SavePath can be saved in DB. Msg += GetFileName(hpf.FileName.ToString()) + " , "; } } lblMsg.Text = Msg + " Uploaded Successfully."; } }
Step 4: Write the private function which helps to Upload files.
This function helps to extract file extension from the fileName.
private string GetFileExtension(string FileName) { char saperator = '.'; string[] temp = FileName.Split(saperator); return "." + temp[1].ToString(); }
OR
private string GetFileExtension(string filePath) { FileInfo fi = new FileInfo(filePath); return fi.Extension; }
This function helps to get Unique Key, which is used to save files on server with different name that does not collied with each other.
private string GetUniqueKey() { int maxSize = 8; char[] chars = new char[62]; string a; a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; chars = a.ToCharArray(); int size = maxSize; byte[] data = new byte[1]; RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); crypto.GetNonZeroBytes(data); size = maxSize; data = new byte[size]; crypto.GetNonZeroBytes(data); StringBuilder result = new StringBuilder(size); foreach (byte b in data) { result.Append(chars[b % (chars.Length - 1)]); } return result.ToString(); }
This function help to get Filename from the filepath.
private string GetFileName(string filePath) { FileInfo fi = new FileInfo(filePath); return fi.Name; }
Step 5: Add Server Side Validation Code
This is the function which is used to validate files that user wants to upload. If the client side validation does not work, this code will help us to identify the invalid files.
Validation rules like whether file type is correct or not, file size is valid or not.
If you do not want to validate the files on server side, you can ignore this code. But I prefer to use it.
private bool ServerSideValidation() { string errorMsg = string.Empty, temp = null; bool errorFlag = true; // Get the HttpFileCollection HttpFileCollection hfc = Request.Files; for (int i = 0; i < hfc.Count; i++) { HttpPostedFile hpf = hfc[i]; if (hpf.ContentLength > 0) { temp = ValidateImage(hpf); if (temp != null) { errorMsg += GetFileName(hpf.FileName.ToString()) + " has error : " + temp; temp = null; } } } if (errorMsg != "") { lblMsg.Text = errorMsg; errorFlag = false; } return errorFlag; }
This function used to check file type & file size. If file is invalid than it will return error message.
private string ValidateImage(HttpPostedFile myFile) { string msg = null; int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileUploadSizeLimit"].ToString()); //Check Length of File is Valid or Not. if (myFile.ContentLength > FileMaxSize) { msg = msg + "File Size is Too Large."; } //Check File Type is Valid or Not. if (!IsValidFile(myFile.FileName)) { msg = msg + "Invalid File Type."; } return msg; }
This function is used to check whether the file that user want to upload is valid file type or not.
private bool IsValidFile(string filePath) { bool isValid = false; string[] fileExtensions = { ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" }; for (int i = 0; i < fileExtensions.Length; i++) { if (filePath.ToUpper().Contains(fileExtensions[i])) { isValid = true; break; } } return isValid; }
Conclusion:
This code is complete solution that helps to upload multiple file using File Upload with jQuery plugin. I was always in a need of such code in my route work so I decided to write the code that helps others also.
Hope this will help !!!
Jay Ganesh
nice post dear…..
thank you, you are very helpful.
I’m from Viet Name.
This article is useful to me and i am looking something more like, is there any way to get the file count in the html where i called the Multifile.js…? lets say that i added 5 file using multifile and deleted 2 from them i should be able to get the count as 3 , Is this possible in Jquery.
http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Examples
I recommend you to put all the extensions in uppercase, and in the comparation compares them with UPPERCASE(), you are doubling the extensions unnecessarily.
I like the example, but you can improve the code
Hi Santiago,
Thanks a lot for improving the code of the article, i have make the changes you suggested.
Hello Ramani,
It your code id nice. it works fine when i m trying it in test project. but when i m trying it in my actual code i have put this is in update panel. on that time it’s not working. so now just want to ask how can i put in the update panel.
Thanks and Advance
Omkar Mhaiskar
Pune.
try this link u will get solution..
https://ramanisandeep.wordpress.com/2008/11/22/file-upload-control-is-not-working-in-update-panel/
if still have query u can ask me
Hello Ramani,
Thanks for such a nice article,
i have the same query as said by Omkar Mhaiskar…
It works fine when we dont use update panel but when the update panel is used it gives the file count as 0
Please help on the same…..
Hi Hasmukh,
The essence of the problem is that the FileUpload control does not work with asynchronous postbacks, and therefore does not work from within an AJAX UpdatePanel.
For Solution Read my post here :
https://ramanisandeep.wordpress.com/2008/11/22/file-upload-control-is-not-working-in-update-panel/
This will help you to understand more about the problem.
Cheers !!!
please disregard previous comment, I got it. 🙂
ok 🙂
Thanx
This code is really helpful to me. but I have question about storing images using this file upload in folder.
B’coz I dont know how many images uploaded by User so I have to dynamically store images in folder. But I tried so much but I couldnt do this. I hope You will help me.
Thanx
Takecare
JSK
Here Step 3 is all about what u r asking me to save multiple file at one go…
Wonderfull work, i was searching for this code for last 2 hours….. only this is simple , helpfull and no heavy plugin needed.
thanks a lot :d
Hey ther is little problem here with me..
when i am trying to upload multiple files….say 5 files at a time page is lossing its connection…………..i mean to say is whole page is crashed.
error in IE is :
“Internet Explorer cannot display the webpage”
what the problem should be ???
the same code is working file with single uploding of file…my code is :
Is there someone who knows the solution ?
If I want to use updatepanel in this page, multiupload doesn’t work..
If you’re okay, pls reply to me how to solve… thanks
try this :
https://ramanisandeep.wordpress.com/2008/11/22/file-upload-control-is-not-working-in-update-panel/
Hope this will help
i want to select at a time more than 5 files. here you given example it’s not working properly so pls help me.
Hi Piyush , what problem you are facing? the code that i have given here is taken from sample application and it was running successfully. Let me know where you are facing problem?
i want to queue in 8 files . and all of them will start uploading on a single button click.. how can it be done, queuing part is ok.
n one more thing, there must be only 1 file type element i.e only one BROWSE input element
You may want to check out the Flajaxian controls – http://www.flajaxian.com/. They give you the ability to select multiple files at once for upload, and the control is free.
But there is no filexible ie: like how to trigger the asp.net button to upload file using FLAJAXIAN fileuploader .. ??
Its only uploading single files donot why
Hi Kiran,
Please check count property of HttpFileCollection object. How many files get posted for it? if it does not gives count more than 1 than you need to check whether you are using multiple fileUpload controls properly or not..
Hope this will give some idea.
Regards,
Sandeep Ramani
Excellent job. thank u very much
Excellent work Sandeep 🙂
Thanks a lot DS 🙂
heyy man,the filupload with multifile.js does not work in update panel.
As u have mentioned in the other link about the postback trigger,that works without the multifile.js file.i need the multifile to work when it is placed in the updatepanel
Hi Venkatesh,
File upload controls do not work in AJAX update panels and the upload control needs to do full page postback. This means that if your upload control is located in an update panel, then the control does not post the file. If you look to the posted file property of the control, you will see it is null. So, the control always has to post full page postback.
To resolve this problem we need to rely upon a standard postback i.e. we need to set the button that is uploading the file to be PostBack trigger instead of AsyncPostBack trigger. This will initiate a normal postback whenever we click the upload button and then it is possible to upload the file.
You need to create a PostBackTrigger for the button that initiates postback like as follows.
Hope this will help !!!
Regards,
Sandeep Ramani
nice post, it work great for me!! thanks Ramani Sandeep.
May I know that how to enable user to select multiple image in File Upload dialog box?? b’coz now I only can select one by one until reach max 5 files. is it possible to do that??
Please check this link for it.
It will help !!!
hi, thanks for reply! that link is really helpful.. thanks Ramani Sandeep 😀
I want to select multiple image in File Upload dialog box. and i already go through the link u provided. but i want it without flash.do u have any other solution without flash?
Hi Hardik,
Have you tried following option:
http://www.flajaxian.com/
http://silverlightfileupld.codeplex.com/
Hope this helps !!!
Sandeep
Thank you ramani sandip
Thanks Ramani Sandeep, Your article really thrilled me. But what if I wanted the user to be able to click + Ctrl on each file and select all before saying ok and uploading? That is you only browse for files once but you select multiple files at once. How do I go about it?
Charles
Nice post
i have a website http://www.cutumb.com/ for wallpapers
i also want to use this script on http://www.cutumb.com/ for uploading wallpapers
i had done in my website multiple file upload it works fine..
when i used the above code it is throwing the error while page is loading : Microsoft JScript runtime error: Object doesn’t support property or method ‘dialog’
Microsoft JScript runtime error: Object doesn’t support property or method ‘fullCalendar’
How can i sort out this?
Thank in advance.
Hello there! Do you know if they make any plugins to help with SEO?
I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good
success. If you know of any please share. Cheers!
thank you very much.. this article was very usefull and acerted for my project. thanks
How significantly of an special post, keep on posting much better half egdbgkfcdkag