Example #1
0
        /// <summary>
        /// Upload a file and return a JSON result
        /// </summary>
        /// <param name="file">The file to upload.</param>
        /// <param name="fileCollection"></param>
        /// <param name="type"> type of upload</param>
        /// <returns>a FileUploadJsonResult</returns>
        /// <remarks>
        /// It is not possible to upload files using the browser's XMLHttpRequest
        /// object. So the jQuery Form Plugin uses a hidden iframe element. For a
        /// JSON response, a ContentType of application/json will cause bad browser
        /// behavior so the content-type must be text/html. Browsers can behave badly
        /// if you return JSON with ContentType of text/html. So you must surround
        /// the JSON in textarea tags. All this is handled nicely in the browser
        /// by the jQuery Form Plugin. But we need to overide the default behavior
        /// of the JsonResult class in order to achieve the desired result.
        /// </remarks>
        /// <seealso cref="http://malsup.com/jquery/form/#code-samples"/>
        //     [Authorize]
        public FileUploadJsonResult AjaxUpload(IEnumerable <HttpPostedFileBase> fileCollection, UploadType type, string uploadPath)
        {
            _type = type;
            // TODO: Add your business logic here and/or save the file
            //System.Threading.Thread.Sleep(2000); // Simulate a long running upload
            // Some browsers send file names with full path. This needs to be stripped.


            //string physicalPath = PathForUpload(file.FileName, 0);


            //// The files are not actually saved in this demo
            //file.SaveAs(physicalPath);
            //lastSavedFile.Add(ResolvePath(physicalPath));
            foreach (string file in Request.Files)
            {
                var      postedFile = Request.Files[file];
                string   thumbPath;
                TimeSpan aduration;
                string   filetype;
                UploadRepository.StoreMediaTemp(HttpContext, postedFile, _type, out thumbPath, out uploadPath, out aduration, out filetype);
                // Return JSON
                if (postedFile != null)
                {
                    if (Request.Url != null)
                    {
                        var result = new FileUploadJsonResult
                        {
                            Data =
                                new
                            {
                                message =
                                    string.Format("Uploaded {0} successfully.", postedFile.FileName),
                                thumbnail        = _path + "/" + thumbPath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty),
                                type             = !String.IsNullOrEmpty(filetype)?filetype : MimeExtensionHelper.FindMime(uploadPath, true),
                                text             = MimeExtensionHelper.FindMime(uploadPath, true).Contains("text") ? thumbPath : "",
                                path             = uploadPath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty),
                                originalFileName = postedFile.FileName,
                                duration         = aduration.ToString()
                            }
                        };
                        return(result);
                    }
                }
            }



            return(new FileUploadJsonResult {
                Data = new { message = "Upload Failed" }
            });
        }
Example #2
0
        public FileUploadJsonResult UploadImage(FormCollection form)
        {
            int max_size = int.Parse(ConfigurationManager.AppSettings["IMAGE_MAX_SIZE"]);

            saveTo = form["path"].Replace("/undefined", "");
            string recordID = form["recordID"];
            string img = form["value"];
            string controller = form["controller"];
            var principal = HttpContext.User as AuthenticationProjectPrincipal;
            FileUploadJsonResult result = new FileUploadJsonResult();
            Message msg = null;
            foreach (string file in Request.Files)
            {
                string uniqueId = DateTime.Now.ToString("MMddyyyyhhmmss");
                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;

                if (hpf.ContentLength != 0)
                {
                    int maxSize = 1024 * 1024 * Constants.IMAGE_MAX_SIZE;
                    //int maxSize = 1024 * 1024 * 2;
                    float sizeFile = float.Parse(hpf.ContentLength.ToString("N"));

                    string extension = Path.GetExtension(hpf.FileName);
                    string[] extAllowList = Constants.IMAGE_EXT_ALLOW.Split(',');
                    if (!extAllowList.Contains(extension.ToLower())) //check extension file is valid
                    {
                        msg = new Message(MessageConstants.E0013, MessageType.Error, extension, Constants.IMAGE_EXT_ALLOW, Constants.IMAGE_MAX_SIZE);
                        result.Data = new { msg };
                    }
                    else if (sizeFile > maxSize) //check maxlength of uploaded file
                    {
                        msg = new Message(MessageConstants.E0012, MessageType.Error, Constants.IMAGE_MAX_SIZE.ToString());
                        result.Data = new { msg };
                    }
                    else  //successful case
                    {

                        string strPath = string.IsNullOrEmpty(recordID) == true ? Server.MapPath(Constants.UPLOAD_TEMP_PATH) : Server.MapPath(saveTo);
                        string imageName = uniqueId + "_" + Path.GetFileName(hpf.FileName);
                        imageName = ConvertUtil.FormatFileName(imageName);
                        hpf.SaveAs(strPath + imageName);
                        if (!string.IsNullOrEmpty(recordID))
                        {
                            switch (controller)
                            {
                                case Constants.CANDIDATE_DEFAULT_VALUE:
                                    Candidate candidateObj = candidateDao.GetById(recordID);
                                    if (candidateObj != null)
                                    {
                                        string oldImgFile = !string.IsNullOrEmpty(candidateObj.Photograph) ? candidateObj.Photograph : string.Empty;
                                        candidateObj.Photograph = imageName;
                                        candidateObj.UpdatedBy = principal.UserData.UserName;
                                        msg = candidateDao.UpdateImage(candidateObj);
                                    }
                                    break;
                                case Constants.STT_DEFAULT_VALUE:
                                    STT sttObj = sttDao.GetById(recordID);
                                    if (sttObj != null)
                                    {
                                        string oldImgFile = !string.IsNullOrEmpty(sttObj.Photograph) ? sttObj.Photograph : string.Empty;
                                        sttObj.Photograph = imageName;
                                        sttObj.UpdatedBy = principal.UserData.UserName;
                                        msg = sttDao.UpdateImage(sttObj);
                                    }
                                    break;
                                case Constants.EMPLOYEE_DEFAULT_VALUE:
                                    Employee emp = empDao.GetById(recordID);
                                    if (emp != null)
                                    {
                                        string oldImgFile = !string.IsNullOrEmpty(emp.Photograph) ? emp.Photograph : string.Empty;
                                        emp.Photograph = imageName;
                                        emp.UpdatedBy = principal.UserData.UserName;
                                        msg = empDao.UpdateImage(emp);
                                    }
                                    break;
                            }
                            if (msg.MsgType != MessageType.Error)
                            {
                                msg = new Message(MessageConstants.I0001, MessageType.Info, imageName, "uploaded");
                            }
                            else
                            {
                                msg = new Message(MessageConstants.E0014, MessageType.Error, "delete photo.");
                            }
                            result.Data = new { msg };
                        }
                        else // case add new
                        {
                            msg = new Message(MessageConstants.I0001, MessageType.Info, imageName, "uploaded");
                            result.Data = new { msg };
                        }
                        if (!String.IsNullOrEmpty(img))
                        {
                            if (System.IO.File.Exists(strPath + img))
                                System.IO.File.Delete(strPath + img);
                        }
                    }
                }
                else
                {
                    msg = new Message(MessageConstants.E0011, MessageType.Error);
                    result.Data = new { msg };
                }
            }
            return result;
        }
Example #3
0
        public FileUploadJsonResult UploadFile(FormCollection form)
        {
            saveTo = form["path"].Replace("/undefined", "");
            string filename = form["value"];
            string recordID = form["recordID"];
            string controller = form["controller"];
            var principal = HttpContext.User as AuthenticationProjectPrincipal;
            FileUploadJsonResult result = new FileUploadJsonResult();
            Message msg = null;
            foreach (string file in Request.Files)
            {
                string uniqueId = DateTime.Now.ToString("MMddyyyyhhmmss");
                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                //string value = form["EmpId"];

                if (hpf.ContentLength != 0)
                {
                    int maxSize = 1024 * 1024 * Constants.CV_MAX_SIZE;
                    float sizeFile = float.Parse(hpf.ContentLength.ToString("N"));

                    string extension = Path.GetExtension(hpf.FileName);
                    string[] extAllowList = Constants.CV_EXT_ALLOW.Split(',');
                    if (!extAllowList.Contains(extension.ToLower())) //check extension file is valid
                    {
                        msg = new Message(MessageConstants.E0013, MessageType.Error, extension, Constants.CV_EXT_ALLOW, Constants.CV_MAX_SIZE.ToString());
                        result.Data = new { msg };
                    }
                    else if (sizeFile > maxSize) //check maxlength of uploaded file
                    {
                        msg = new Message(MessageConstants.E0012, MessageType.Error, Constants.CV_MAX_SIZE.ToString());
                        result.Data = new { msg };
                    }
                    else  //successful case
                    {
                        //string strPath = Server.MapPath(saveTo);
                        string strPath = string.IsNullOrEmpty(recordID) == true ? Server.MapPath(Constants.UPLOAD_TEMP_PATH) : Server.MapPath(saveTo);
                        string cvName = uniqueId + "_" + Path.GetFileName(hpf.FileName);
                        cvName = ConvertUtil.FormatFileName(cvName);
                        hpf.SaveAs(strPath + cvName);

                        if (!string.IsNullOrEmpty(recordID))
                        {
                            switch (controller)
                            {
                                case "Candidate":
                                    Candidate candidateObj = candidateDao.GetById(recordID);
                                    if (candidateObj != null)
                                    {
                                        candidateObj.CVFile = cvName;
                                        candidateObj.UpdatedBy = principal.UserData.UserName;
                                        msg = candidateDao.UpdateFile(candidateObj);
                                    }
                                    break;
                                case "STT":
                                    STT sttObj = sttDao.GetById(recordID);
                                    if (sttObj != null)
                                    {
                                        sttObj.CVFile = cvName;
                                        sttObj.UpdatedBy = principal.UserData.UserName;
                                        msg = sttDao.UpdateCV(sttObj);
                                    }
                                    break;
                                case "Employee":
                                    Employee emp = empDao.GetById(recordID);
                                    if (emp != null)
                                    {
                                        emp.CVFile = cvName;
                                        emp.UpdatedBy = principal.UserData.UserName;
                                        msg = empDao.UpdateCV(emp);
                                    }
                                    break;
                            }
                            if (msg.MsgType != MessageType.Error)
                            {
                                msg = new Message(MessageConstants.I0001, MessageType.Info, cvName, "uploaded");
                            }
                            else
                            {
                                msg = new Message(MessageConstants.E0014, MessageType.Error, "delete CV.");
                            }
                            result.Data = new { msg };
                        }
                        else // Case when Create
                        {
                            msg = new Message(MessageConstants.I0001, MessageType.Info, cvName, "uploaded");
                            result.Data = new { msg };
                        }
                        if (!String.IsNullOrEmpty(filename))
                        {
                            if (System.IO.File.Exists(strPath + filename))
                                System.IO.File.Delete(strPath + filename);
                        }
                    }

                }
                else
                {
                    msg = new Message(MessageConstants.E0011, MessageType.Error);
                    result.Data = new { msg };

                }
            }
            return result;
        }