"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Tuesday, July 26, 2011

Fileupload in asp.net c#

Hi *.*,
2 day's before i got a mail from one of reader regarding fileupload control in asp.net.He had certain needs also...
  • Upload file to particular folder
  • Get extension of file(Before Uploading)
  • Save file in custom name
  • Get Size of the file
  • Server side and Client side validation
 Here it go...

Add a new fileupload control
                <td>
                    &nbsp;<asp:FileUpload ID="lmgUpload" runat="server" />
                </td>
 

On server side
public void Fileupload()
    {
        if (lmgUpload.HasFile) // Server Side validation
        {
            string _FilePath = lmgUpload.PostedFile.FileName; //  File Path [ Client Side ]
            string _Size = lmgUpload.PostedFile.ContentLength.ToString(); 
// Size of file in bytes
            string pat = @"\\(?:.+)\\(.+)\.(.+)";
            Regex r = new Regex(pat);
            Match m = r.Match(_FilePath);
            string file_ext = m.Groups[2].Captures[0].ToString(); //  Extension 
            string file_Name = txt_BrandName.Text.ToString().Trim() + "." + file_ext; // Adding custom Name
            lmgUpload.PostedFile.SaveAs(Server.MapPath(".\\img\\") + file_Name); 
// Saving file to Custom folder  [ img ]
            
        }
        else
        {
            string _Errmsg = "Select Image first !!!!";
        }
        
    }

Add a name space
Because of reason of using regular expression on server side, v need to add a namespace:

using System.Text.RegularExpressions;


For ClientSide validation:
I already posted that Checkout here:FileUpload Javascript Validation

If FileUpload control inside the Ajax UpdatePanel Checkout here:FileUpload inside the Ajax UpdatePanel


and finally finished with a smile... For trouble shoot contact me....

Stay Tune... 

Have a nice day... 'N happy Coding :)

No comments: