Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
Dear Code Project Expert Team,
I have big issue when we upload file for upload mechanism. And also want to Percentage completion done and display of completion process on front.
All of working fine file upload and complete successfully done.
But process bar not working on server. i retrieve completion % in session. But session not working in PageMethods on Live server. Also all of functionality working in LOCALHOST.
 
STEP : 1 Uploading File
if (((SessionBasket)(Session["SessionHandler"])) != null)
            {
                if (((((SessionBasket)(Session["SessionHandler"])).UserID) != null) || ((((SessionBasket)(Session["SessionHandler"])).UserID) != ""))
                {
                    UploadDetail Upload = (UploadDetail)HttpContext.Current.Session["UploadDetail"];
 
                    #region "Post Back"
                    if (this.IsPostBack)
                    {
                        if (Upload != null)
                        {
                            if ((Upload.CourseId != null) && (Upload.CourseName != null))
                            {
 
                                // UploadDetail Upload = (UploadDetail)this.Session["UploadDetail"];
                                //Let the webservie know that we are not yet ready
                                Upload.IsReady = false;
                                if (this.fileUpload.PostedFile != null && this.fileUpload.PostedFile.ContentLength > 0)
                                {
 
                                    //build the local path where upload all the files

                                    //Comment Code
                                    string MainPath = this.Server.MapPath(@"../../UploadCourses");
 
                                    // string MainPath = "D:\\Rohit\\Project 2013\\Upload";

 
                                    // Create Main Folder if Not Exists
                                    if (!Directory.Exists(MainPath))
                                    {
                                        Directory.CreateDirectory(MainPath);
                                    }
                                    string subFolderName = (((SessionBasket)(Session["SessionHandler"])).AccName).ToString() + "_Courses";
                                    // Check Sub Folder Exists
                                    if (!Directory.Exists(Path.Combine(MainPath, subFolderName)))
                                    {
                                        //Not exists, create subDir folder under Uploads folder
                                        Directory.CreateDirectory(Path.Combine(MainPath, subFolderName));
                                    }
 
                                    string subFolderPath = MainPath + "\\" + subFolderName;
 
                                    ///// Create Sub Folder Course Name
                                    string subCourseFolderName = Upload.CourseName;
                                    // Check Sub Folder Exists
                                    if (!Directory.Exists(Path.Combine(subFolderPath, subCourseFolderName)))
                                    {
 
                                        //Not exists, create subDir folder under Uploads folder
                                        Directory.CreateDirectory(Path.Combine(subFolderPath, subCourseFolderName));
 
                                    }
 
                                    //build the local path where upload all the files and Account Folder Name
                                    //Comment Code
                                    string path = this.Server.MapPath(@"../../UploadCourses/" + subFolderName + "\\" + subCourseFolderName);
 

                                    //string path = "D:\\Rohit\\Project 2013\\Upload\\" + subFolderName + "\\" + subCourseFolderName;

 
                                    string fileName = Path.GetFileName(this.fileUpload.PostedFile.FileName);
                                    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(this.fileUpload.PostedFile.FileName);
 
                                    // Delete All Existing File
                                    string[] filePaths = Directory.GetFiles(path);
                                    foreach (string filePath in filePaths)
                                        File.Delete(filePath);
 

                                    // Delete All Existing Subfolder

                                    string[] delSubfolder = Directory.GetDirectories(path);
                                    foreach (string FolderPath in delSubfolder)
                                    {
                                        DirectoryInfo deldirectory = new DirectoryInfo(FolderPath);
                                        deldirectory.Delete(true);
                                    }
 

 

                                    //Build the strucutre and stuff it into session
                                    Upload.ContentLength = this.fileUpload.PostedFile.ContentLength;
                                    Upload.FileName = fileName;
                                    Upload.UploadedLength = 0;
                                    //Let the polling process know that we are done initializing ...
                                    Upload.IsReady = true;
 
                                    //set the buffer size to something larger.
                                    //the smaller the buffer the longer it will take to download, 
                                    //but the more precise your progress bar will be.
                                    int bufferSize = 1024;
                                    byte[] buffer = new byte[bufferSize];
 
                                    //Writing the byte to disk
                                    using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create))
                                    {
                                        //Aslong was we haven't written everything ...
                                        while (Upload.UploadedLength < Upload.ContentLength)
                                        {
                                            //Fill the buffer from the input stream
                                            int bytes = this.fileUpload.PostedFile.InputStream.Read(buffer, 0, bufferSize);
                                            //Writing the bytes to the file stream
                                            fs.Write(buffer, 0, bytes);
                                            //Update the number the webservice is polling on to the session
                                            Upload.UploadedLength += bytes;
 
                                        }
                                    }
 
                                    //Extarct Zip file 

                                    string strZipFolderName = ExtarctZipFile(path + "\\" + fileName, path);
 
                                    //Comment Code
                                    string strFileVirtualPath = "\\UploadCourses\\" + subFolderName + "\\" + subCourseFolderName + "\\" + strZipFolderName;
                                    //string strFileVirtualPath = "D:\\Rohit\\Project 2013\\Upload\\" + subFolderName + "\\" + subCourseFolderName + "\\" + fileNameWithoutExtension;

 
                                    // imsmanifest.xml file find
                                    //Comment Code
                                    string strImanifestPathRead = this.Server.MapPath(@"../../UploadCourses/" + subFolderName + "\\" + subCourseFolderName + "\\" + strZipFolderName);
 
                                    //// string strImanifestPathRead = "D:\\Rohit\\Project 2013\\Upload\\" + subFolderName + "\\" + subCourseFolderName + "\\" + fileNameWithoutExtension;

                                    // check for scorm or non scorm file 
                                    if (Upload.ScormCheckId == 2)
                                    {
                                        int intManifest = File_Imsmanifest_Identify_Resources(strImanifestPathRead);
                                        if (intManifest == 0)
                                        {
                                            // Delete All Existing Subfolder if imanifest file not exists

                                            string[] strDelSubfolder = Directory.GetDirectories(path);
                                            foreach (string strFolderPath in strDelSubfolder)
                                            {
                                                DirectoryInfo dideldirectory = new DirectoryInfo(strFolderPath);
                                                dideldirectory.Delete(true);
                                            }
 
                                            //Call parent page know we have processed the uplaod
                                            const string js = "window.parent.onComplete(4,'Course does not contain imanifest file.','{0}','{1} of {2} Bytes');";
                                            ScriptManager.RegisterStartupScript(this, typeof(AUI_Course_UploadEngine), "progress", string.Format(js, fileName, Upload.UploadedLength, Upload.ContentLength), true);
 
                                        }
                                        if (intManifest == 1)
                                        {
                                            Utility objUtility = new Utility();
                                            strimanifestfile = objUtility.ManifestRead(strImanifestPathRead + "\\imsmanifest.xml", "file", strImanifestPathRead);
                                        }
 
                                    }
                                    // Database insert for scorm or non scorm file 

                                    #region "Scorm and non scorm file checking and database insert"
                                    if ((Upload.ScormCheckId == 1) || (Upload.ScormCheckId == 2))
                                    {
                                        objCourseManagement = new CourseManagement();
                                        objBAL_AUI_CourseManagement = new BAL_AUI_CourseManagement();
 
                                        #region "Scorm Manifest file checking"
                                        if (Upload.ScormCheckId == 2)
                                        {
                                            if ((strimanifestfile == "Mapping Right"))
                                            {
                                                //Response.Write("CourseID=" + Upload.CourseId);
                                                //Response.Write("CourseID=" + Upload.CourseId);
                                                //Course Infromation Store In Database

                                                objCourseManagement.CourseId = Upload.CourseId;
                                                objCourseManagement.FileName = fileName.Trim();
                                                objCourseManagement.DocumentLink = strFileVirtualPath;
                                                objCourseManagement.Size = CalculateFileSize(Upload.ContentLength);
                                                objCourseManagement.Guid = System.Guid.NewGuid().ToString();
                                                objCourseManagement.CreatedBy = Convert.ToInt32((((SessionBasket)(Session["SessionHandler"])).UserID).ToString());
                                                dsResult = objBAL_AUI_CourseManagement.Insert_Course_DocumentDetails(objCourseManagement);
                                                if (dsResult.Tables[0].Rows.Count > 0)
                                                {
                                                    //Update FileName Version Size parent page know we have processed the uplaod
                                                    const string fn = "window.parent.onCompleteFileVersion(1,'File uploaded successfully.','{0}','{1} of {2} Bytes','{3}','{4}');";
 
                                                    ScriptManager.RegisterStartupScript(this, typeof(AUI_Course_UploadEngine), "progress", string.Format(fn, fileName, Upload.UploadedLength, Upload.UploadedLength, dsResult.Tables[0].Rows[0]["Version"].ToString(), dsResult.Tables[0].Rows[0]["Size"].ToString()), true);
                                                }
 
                                                else
                                                {
 
                                                    //Call parent page know we have processed the uplaod
                                                    const string js = "window.parent.onComplete(1,'File uploaded successfully but Course not enter in Database .','{0}','{1} of {2} Bytes');";
                                                    ScriptManager.RegisterStartupScript(this, typeof(AUI_Course_UploadEngine), "progress", string.Format(js, fileName, Upload.UploadedLength, Upload.ContentLength), true);
 
                                                }
 

 
                                                //Call parent page know we have processed the uplaod
                                                //const string js = "window.parent.onComplete(1,'File uploaded successfully.','{0}','{1} of {2} Bytes');";
                                                //ScriptManager.RegisterStartupScript(this, typeof(AUI_Course_UploadEngine), "progress", string.Format(js, fileName, Upload.UploadedLength, Upload.ContentLength), true);
                                            }
                                            else
                                            {
                                                // Delete All Existing Subfolder if imanifest file rescourse mapping not correct

                                                string[] strDelSubfolder = Directory.GetDirectories(path);
                                                foreach (string strFolderPath in strDelSubfolder)
                                                {
                                                    DirectoryInfo dideldirectory = new DirectoryInfo(strFolderPath);
                                                    dideldirectory.Delete(true);
                                                }
 
                                                //Call parent page know we have processed the uplaod
                                                const string js = "window.parent.onComplete(4,'Mainfest File resources missing','{0}','{1} of {2} Bytes');";
                                                ScriptManager.RegisterStartupScript(this, typeof(AUI_Course_UploadEngine), "progress", string.Format(js, fileName, Upload.UploadedLength, Upload.ContentLength), true);
 
                                            }
                                        }
                                        #endregion
                                        #region "Non scrom file database insert"
                                        if (Upload.ScormCheckId == 1)
                                        {
                                            objCourseManagement.CourseId = Upload.CourseId;
                                            objCourseManagement.FileName = fileName.Trim();
                                            objCourseManagement.DocumentLink = strFileVirtualPath;
                                            objCourseManagement.Size = CalculateFileSize(Upload.ContentLength);
                                            objCourseManagement.Guid = System.Guid.NewGuid().ToString();
                                            objCourseManagement.CreatedBy = Convert.ToInt32((((SessionBasket)(Session["SessionHandler"])).UserID).ToString());
                                            dsResult = objBAL_AUI_CourseManagement.Insert_Course_DocumentDetails(objCourseManagement);
                                            if (dsResult.Tables[0].Rows.Count > 0)
                                            {
                                                //Update FileName Version Size parent page know we have processed the uplaod
                                                const string fn = "window.parent.onCompleteFileVersion(1,'File uploaded successfully.','{0}','{1} of {2} Bytes','{3}','{4}');";
 
                                                ScriptManager.RegisterStartupScript(this, typeof(AUI_Course_UploadEngine), "progress", string.Format(fn, fileName, Upload.UploadedLength, Upload.UploadedLength, dsResult.Tables[0].Rows[0]["Version"].ToString(), dsResult.Tables[0].Rows[0]["Size"].ToString()), true);
                                            }
 
                                            else
                                            {
 
                                                //Call parent page know we have processed the uplaod
                                                const string js = "window.parent.onComplete(1,'File uploaded successfully but Course not enter in Database .','{0}','{1} of {2} Bytes');";
                                                ScriptManager.RegisterStartupScript(this, typeof(AUI_Course_UploadEngine), "progress", string.Format(js, fileName, Upload.UploadedLength, Upload.ContentLength), true);
 
                                            }
                                        }
                                        #endregion
                                    }
                                    #endregion
                                }
                                else
                                {
                                    //Call parent page know we have processed the uplaod
                                    const string js = "window.parent.onComplete(4, 'There was a problem with the file.','','0 of 0 Bytes');";
                                    ScriptManager.RegisterStartupScript(this, typeof(AUI_Course_UploadEngine), "progress", js, true);
                                }
                                //Let webservie know that we are not yet ready
                                Upload.IsReady = false;
 
                            }
                            else
                            {
                                //Call parent page know session will be expiry
                                const string js = "window.parent.onComplete(4,'Course have been expired please close window and select again.','{0}','{1} of {2} Bytes');";
                                ScriptManager.RegisterStartupScript(this, typeof(AUI_Course_UploadEngine), "progress", string.Format(js, "NO file", "0", "0"), true);
                            }
                        }
 
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, GetType(), "Upload Class Missing", "alert('Upload Missing')", true);
                            Response.Redirect("AUI_Login.aspx?OutUpload=ss", false);
                        }
                    }
                    #endregion
                }
            }
            else
            {
                //Call parent page know session will be expiry
                const string js = "window.parent.onComplete(4,'Session expired please login again.','{0}','{1} of {2} Bytes');";
                ScriptManager.RegisterStartupScript(this, typeof(AUI_Course_UploadEngine), "progress", string.Format(js, "NO file", "0", "0"), true);
 
            }

STEP : 2 Uploading File JAVASCRIPT CALL PAGE METHODS SERVER SIDE
 
intervalID = window.setInterval(function() {
                        PageMethods.GetUploadStatus(function(result) {
                            // alert(result + 'Object');
                            //alert(result.message + 'Message');
                            if (result) {
                                setProgress(result.percentComplete);
                                //Upadte the message every 500 milisecond
                                updateMessage(MessageStatus.Information, result.message, result.fileName, result.downloadBytes);
                                if (result == 100) {
                                    //clear the interval
                                    window.clearInterval(intervalID);
                                    clearTimeout(subintervalID);
                                }
                            }
                        });
                    }, 500);

STEP : 3 Uploading File Process Bar % Completion
 
#region Web Methods
 
    [System.Web.Services.WebMethod(EnableSession = true)]
    [System.Web.Script.Services.ScriptMethod]
    public static object GetUploadStatus()
    {
 
        //Get the length of the file on disk and divide that by the length of the stream
        UploadDetail info = (UploadDetail)HttpContext.Current.Session["UploadDetail"];
        // UploadDetail tets = (UploadDetail)Session["UploadDetail"];

        if (info != null && info.IsReady)
        {
            int soFar = info.UploadedLength;
            int total = info.ContentLength;
            int percentComplete = (int)Math.Ceiling((double)soFar / (double)total * 100);
            string message = "Uploading...";
            string fileName = string.Format("{0}", info.FileName);
            string downloadBytes = string.Format("{0} of {1} Bytes", soFar, total);
            return new
            {
                percentComplete = percentComplete,
                message = message,
                fileName = fileName,
                downloadBytes = downloadBytes
            };
        }
        //Not ready yet
        return null;
    }
 
    #endregion
Posted 30-Apr-13 0:42am
Comments
ryanb31 at 30-Apr-13 7:04am
   
Your live server is likely part of a web farm and session will need to be moved into SQL.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 480
1 Maciej Los 290
2 Richard MacCutchan 225
3 BillWoodruff 185
4 Suraj Sahoo | Coding Passion 155
0 OriginalGriff 8,764
1 Sergey Alexandrovich Kryukov 7,437
2 DamithSL 5,639
3 Maciej Los 5,279
4 Manas Bhardwaj 4,986


Advertise | Privacy | Mobile
Web01 | 2.8.1411028.1 | Last Updated 30 Apr 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100