Total Pageviews

Thursday, May 14, 2009

Generate Unique Name for Uploading File

Use following function to generate unique file name.
===================================== here i m uploading image file....so i have checked image file extension and its size too....

private string Save_InFolder()
{
    if (Validate_Image() == false)
    {
        HttpPostedFile hpf = fuBrandImage.PostedFile;
        string savePath = ConfigurationManager.AppSettings["CategoryImagePath"].ToString();
        /*  string savePath = ConfigurationManager.AppSettings["CategoryImagePath"].ToString();  
         * the path is defined in web.config file like defined in appsetting section.. 
         * add  follwoing line in your appsetting section of webconfig  add key="CategoryImagePath" value="~/Images/Category/" 
         * // this is where u save the file...  
         */
        string fileName = GetUniqueKey() + GetFileExtension(hpf.FileName);
        string saveName = Server.MapPath(savePath) + fileName;

        //--------------Save Image into  Folder---------------         
        hpf.SaveAs(saveName);
        //--------------Save Image Path into Database---------         
        savePath = savePath + fileName;
        return savePath;
    }
    return null;
}

//check file extension 
private string GetFileExtension(string FileName)
{
    char saperator = '.';
    string[] temp = FileName.Split(saperator);
    return "." + temp[1].ToString();
}

private bool Validate_Image()
{
    bool errorFlag = false;
    string errorMessage = null;
    // Get a reference to PostedFile object     
    HttpPostedFile myFile = fuBrandImage.PostedFile;
    errorMessage = ValidateImage(myFile);
    if (errorMessage != null)
    {
        ShowMessage(errorMessage);
        errorFlag = true;
    }
    return errorFlag;
}

private string ValidateImage(HttpPostedFile myFile)
{
    string msg = null;
    //Check Length of File is Valid or Not.     
    int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["QueryFileAttachmentSize"].ToString());
    if (myFile.ContentLength > FileMaxSize)
    {
        msg = msg + "File Size is Too Large.";
    }
    //Check File Type is Valid or Not.        
    if (!IsValidFile(myFile.FileName))
    {
        //File Type Error                
        msg = msg + "Upload Only (.bmp, .jpg, .png, .gif, .jpeg )Image .";
    }
    return msg;
}

private bool IsValidFile(string filePath)
{
    bool isValid = false;
    string[] fileExtensions = { ".bmp", ".jpg", ".png", ".gif", ".jpeg", ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };
    for (int i = 0; i < fileExtensions.Length; i++)
    {
        //get file extensions and check
    }
}

No comments:

Post a Comment

Blog Archive

Ideal SQL Query For Handling Error & Transcation in MS SQL

BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...