Saturday, 10 October 2015

Asp.Net Fileupload along with validations save in folder, database in binary format along with thumb nail

(1)Javascript to validate fileformate
=============================================================
<script src="Scripts/jquery-1.7.1.js"></script>
    <script type="text/javascript">
        function ValidateFile() {
            var fileControlValue = document.getElementById("<%=fileUpload.ClientID%>").value;
            var msg = "Please Fille the bellow missing fields";
            var isFocus = false;
            if (fileControlValue == "" || fileControlValue == null) {
                msg = msg + "\n -Select the file";
                if (isFocus == false) {
                    document.getElementById("<%=fileUpload.ClientID%>").focus();
                }
            }
            if (msg != "Please Fille the bellow missing fields") {
                alert(msg);
                return false;
            }
            else {
                if (!validateFileFormate()) {
                    alert("Invalid file formate.File formate must be .doc,.jpg,.png,.docx,.xls");
                    return false;
                }
            }
            return true;
        }
        function validateFileFormate() {
            var fileControlValue = document.getElementById("<%=fileUpload.ClientID%>").value;
            var docType = fileControlValue.substr(fileControlValue.lastIndexOf('.'), fileControlValue.Length);
            var allowFileType = new Array(".doc", ".jpg", ".png", ".docx", ".xls", ".xlsx");
            if (allowFileType.indexOf(docType) > -1) {
                return true;
            }
            return false;
        }
    </script>

(2)Save file in folder
========================================================

string filePath = Server.MapPath("~") + ConfigurationManager.AppSettings["FilesPath"];
                string fileName = fileUpload.FileName;
                string fileType = fileName.Substring(fileName.LastIndexOf("."));
                string targetFilePath = string.Empty;
                targetFilePath = filePath + fileName.Substring(0, fileUpload.FileName.LastIndexOf(".")) + DateTime.Now.GetHashCode() + fileType;
                FileDetails.CreateBy = 1;
                FileDetails.FileName = fileName;
                FileDetails.FilePath = targetFilePath;
                FileDetails.FileType = fileType;

                fileUpload.PostedFile.SaveAs(targetFilePath);

(3)Save file in database in binary formate along with thumb nail
================================================================

                string fileName = fileUpload.FileName;
                string fileType = fileName.Substring(fileName.LastIndexOf("."));
                FileDetails.CreateBy = 1;
                FileDetails.FileName = fileName;
                FileDetails.FilePath = CreateThumbNail();
                FileDetails.FileType = fileType;
                FileDetails.FileBinaryData = ConvertToBinaryFormate(FileDetails.FilePath);
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connectionstring"].ToString());
                SqlCommand cmd = new SqlCommand("SP_INSERTFILEINFO", con);
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                cmd.Parameters.AddWithValue("@FileName", FileDetails.FileName);
                cmd.Parameters.AddWithValue("@FileType", FileDetails.FileType);
                cmd.Parameters.AddWithValue("@FilePath", FileDetails.FilePath);
                cmd.Parameters.AddWithValue("@FileBinaryData", FileDetails.FileBinaryData);
                cmd.Parameters.AddWithValue("@CreateBy", FileDetails.CreateBy);
                cmd.Parameters.AddWithValue("@IDVALUE", "");

                int output = cmd.ExecuteNonQuery();
                con.Close();

 protected byte[] ConvertToBinaryFormate(string filePath)
    {
        byte[] img=new byte[5];
        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        img = new byte[fs.Length];
        fs.Read(img, 0, (int)fs.Length);
        fs.Close();
        return img;
    }

 protected bool ThumbnailCallback()
    {
        return true;
    }
protected string CreateThumbNail()
    {
        string filePath = Server.MapPath("~") + ConfigurationManager.AppSettings["FilesPath"];
        string fileName = fileUpload.FileName;
        string fileType = fileName.Substring(fileName.LastIndexOf("."));
        string targetFilePath = string.Empty;
        targetFilePath = filePath + fileName.Substring(0, fileName.LastIndexOf(".")) + DateTime.Now.GetHashCode() + fileType;
        string Destination = filePath + fileName.Substring(0, fileName.LastIndexOf(".")) + DateTime.Now.GetHashCode() + "Tumb" + fileType;
        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }
        fileUpload.PostedFile.SaveAs(targetFilePath);

        System.Drawing.Image objImage = System.Drawing.Image.FromFile(targetFilePath);
        System.Drawing.Imaging.ImageFormat imgFormat = objImage.RawFormat;

        int newImageHeight = objImage.Height;
        int newImageWidth = objImage.Width;

        int targetImageHeight = 100;
        int targetImageWidth = 150;


        if (targetImageHeight > 100 || targetImageWidth > 100)
        {
            targetImageHeight = 100;
            targetImageWidth = 100;
        }

        if (newImageHeight > targetImageHeight || newImageWidth > targetImageWidth)
        {
            if (newImageWidth * (targetImageHeight / targetImageWidth) > newImageHeight)
            {

                newImageHeight = (targetImageWidth * newImageHeight) / newImageWidth;
                newImageWidth = targetImageWidth;
            }
            else
            {
                newImageWidth = (targetImageHeight * newImageWidth) / newImageHeight;
                newImageHeight = targetImageHeight;
            }
        }
        System.Drawing.Image myThumbNail = new System.Drawing.Bitmap(newImageWidth, newImageHeight, objImage.PixelFormat);
        myThumbNail = objImage.GetThumbnailImage(newImageWidth, newImageHeight,new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
        myThumbNail.Save(Destination);
        objImage.Dispose();
        myThumbNail.Dispose();
        return Destination;
    }

(4)Web.config
=======================================================
 <add key="FilesPath" value='UploadedFike\'/>

No comments:

Post a Comment