Ejemplo n.º 1
0
        public JsonResult Upload()
        {
            var list = new List <object>();

            for (int i = 0; i < Request.Files.Count; i++)
            {
                string filename = DateTime.Now.ToString("yyyyMMddHHmmssss") + Request.Files[i].FileName;
                string path     = System.IO.Path.Combine(Server.MapPath("~/Uploads/Products"), filename);
                Request.Files[i].SaveAs(path);

                ImageResizer resizer = new ImageResizer(path);
                resizer.Resize(168, 168, ImageEncoding.Jpg90);
                string thumPath = System.IO.Path.Combine(Server.MapPath("~/Uploads/Products/Thumbnail"), filename);
                resizer.SaveToFile(thumPath);

                var obj = new
                {
                    filename,
                    url = "/Uploads/Products/Thumbnail/" + filename
                };
                list.Add(obj);
            }

            return(Json(new
            {
                status = 200,
                data = list
            }, JsonRequestBehavior.AllowGet));
        }
        private static string GetResizedImagePath(string filepath, int width, int height)
        {
            string resizedPath = filepath;

            if (width > 0 || height > 0)
            {
                resizedPath = filepath.GetPathForResizedImage(width, height);

                if (!Directory.Exists(resizedPath))
                    Directory.CreateDirectory(new FileInfo(resizedPath).DirectoryName);

                if (!File.Exists(resizedPath))
                {
                    var imageResizer = new ImageResizer(filepath);
                    if (width > 0 && height > 0)
                    {
                        imageResizer.Resize(width, height, ImageEncoding.Jpg90);
                    }
                    else if (width > 0)
                    {
                        imageResizer.Resize(width, ImageEncoding.Jpg90);
                    }
                    imageResizer.SaveToFile(resizedPath);
                    imageResizer.Dispose();
                }
            }
            return resizedPath;
        }
Ejemplo n.º 3
0
        public JsonResult Upload()
        {
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssss") + Request.Files[0].FileName.Replace(" ", "");
            string path     = Path.Combine(Server.MapPath("~/Public/Upload/Profiles"), fileName);

            Request.Files[0].SaveAs(path);

            ImageResizer resizer = new ImageResizer(path);

            resizer.Resize(40, 40, ImageEncoding.Jpg90);
            string thumPath = Path.Combine(Server.MapPath("~/Public/Upload/Profiles/ProfileThumbnails"), fileName);

            resizer.SaveToFile(thumPath);


            return(Json(new
            {
                status = 200,
                data = new
                {
                    fileUrl = "/Upload/Profiles/" + fileName,
                    fileName
                }
            }, JsonRequestBehavior.AllowGet));
        }
        private static string GetResizedImagePath(string filepath, int width, int height)
        {
            string resizedPath = filepath;

            if (width > 0 || height > 0)
            {
                resizedPath = filepath.GetPathForResizedImage(width, height);

                if (!Directory.Exists(resizedPath))
                {
                    Directory.CreateDirectory(new FileInfo(resizedPath).DirectoryName);
                }

                if (!File.Exists(resizedPath))
                {
                    var imageResizer = new ImageResizer(filepath);
                    if (width > 0 && height > 0)
                    {
                        imageResizer.Resize(width, height, ImageEncoding.Jpg90);
                    }
                    else if (width > 0)
                    {
                        imageResizer.Resize(width, ImageEncoding.Jpg90);
                    }
                    imageResizer.SaveToFile(resizedPath);
                    imageResizer.Dispose();
                }
            }
            return(resizedPath);
        }
Ejemplo n.º 5
0
        private Image cropImage(string image)
        {
            ImageResizer resizer = new ImageResizer(image);
            // resize to 400 px, jpg quality 90
            var byteArray1 = resizer.Resize(1024, ImageEncoding.Jpg100);

            // save last resized image to file
            resizer.SaveToFile(Application.StartupPath + "\\" + System.IO.Path.GetFileName(image));
            Image i = Image.FromFile(Application.StartupPath + "\\" + System.IO.Path.GetFileName(image));

            return(i);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets the resized image path.
        /// </summary>
        /// <param name="filepath">The filepath.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <returns></returns>
        public static string GetResizedImagePath(string filepath, int width, int height)
        {
            var resizedPath = filepath;

            try
            {
                if (width > 0 || height > 0)
                {
                    resizedPath = GetPathForResizedImage(filepath, width, height);

                    if (!Directory.Exists(resizedPath))
                    {
                        var fileInfo = new FileInfo(resizedPath);
                        if (!string.IsNullOrEmpty(fileInfo.DirectoryName))
                        {
                            Directory.CreateDirectory(fileInfo.DirectoryName);
                        }
                    }

                    if (!File.Exists(resizedPath))
                    {
                        var imageResizer = new ImageResizer(filepath);
                        if (width > 0 && height > 0)
                        {
                            imageResizer.Resize(width, height, ImageEncoding.Jpg90);
                        }
                        else if (width > 0)
                        {
                            imageResizer.Resize(width, ImageEncoding.Jpg90);
                        }
                        imageResizer.SaveToFile(resizedPath);
                        imageResizer.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("Failed to get resized image path - error: {0}", ex.ToString());
            }

            return(resizedPath);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// accept file from content question in src img tag. Move file from srcFolder to destFolder
        /// </summary>
        /// <param name="content">Content Question with html code</param>
        /// <param name="srcFolder">folder include image file</param>
        /// <param name="destFolder">folder save image file</param>
        /// <param name="w">with image when resize</param>
        /// <param name="h">height image when resize</param>
        /// <param name="encoding">image encoding</param>
        private void AcceptFile(string content, string srcFolder, string destFolder, int w, int h, ImageEncoding encoding)
        {
            try
            {
                if (w <= 0 || h <= 0)
                {
                    AcceptFile(content, srcFolder, destFolder);
                }

                if (!Directory.Exists(srcFolder))
                {
                    throw new FileNotFoundException("Thu m?c ch?a ?nh không t?n t?i", srcFolder);
                }
                if (!Directory.Exists(destFolder))
                {
                    Directory.CreateDirectory(destFolder);
                }
                var files = GetFileName(content);

                foreach (var fileName in files)
                {
                    if (System.IO.File.Exists(srcFolder + fileName))
                    {
                        if (System.IO.File.Exists(destFolder + fileName))
                        {
                            System.IO.File.Delete(destFolder + fileName);
                        }
                        System.IO.File.Copy(srcFolder + fileName, destFolder + fileName);
                        var resize = new ImageResizer(destFolder + fileName);
                        resize.Resize(w, h, encoding);
                        resize.SaveToFile(destFolder + fileName);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// The method for handling upload a file to server
        /// </summary>
        /// <param name="file">
        /// The file will be uploaded to server
        /// </param>
        /// <param name="maximumWidth">
        /// Maximum width
        /// </param>
        /// <param name="storagePath">
        /// The directory which the file will be stored in
        /// </param>
        /// <param name="fileName">
        /// fileName will be created based on DateTime.Now
        /// as binary string and uploaded file extension
        /// </param>
        public static bool UploadAndResizeFile(HttpPostedFile file, int maximumWidth,
                                               string storagePath, ref string fileName)
        {
            var result = true;

            try
            {
                // Get storage upload path
                var fileInfo = new FileInfo(file.FileName);
                fileName = DateTime.Now.ToBinary() + fileInfo.Extension;
                var fullStoragePath = Path.Combine(storagePath, fileName);

                // Get to be uploaded image width
                using (Image sourceImage = Image.FromStream(file.InputStream))
                {
                    var uploadImageWidth = sourceImage.Width;

                    if (uploadImageWidth > maximumWidth)
                    {
                        var fileByteArray = ConvertImageToByteArray(sourceImage, fileInfo.Extension);
                        var imageResizer  = new ImageResizer(fileByteArray);
                        imageResizer.Resize(maximumWidth, ImageEncoding.Jpg90);
                        imageResizer.SaveToFile(fullStoragePath);
                        imageResizer.Dispose();
                    }
                    else
                    {
                        file.SaveAs(fullStoragePath);
                    }
                }
            }
            catch (Exception ex)
            {
                result = false;
                Logger.ErrorFormat("UploadAndResizeFile: {0}", ex.ToString());
            }
            return(result);
        }
Ejemplo n.º 9
0
        public ActionResult Register(RegisterModel model)
        {
            int?companyID = db.Users.Find(WebSecurity.CurrentUserId).companyID;

            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    string imageUrl  = "";
                    var    imageGUID = Guid.NewGuid();
                    if (model.image != null)
                    {
                        imageUrl = imageGUID +
                                   Path.GetExtension(model.image.FileName);
                        string filePath = Path.Combine(
                            Server.MapPath("~/Uploads/UserImages"),
                            imageGUID + Path.GetExtension(model.image.FileName
                                                          ));
                        if (model.image.ContentLength > 102400)
                        {
                            MemoryStream target = new MemoryStream();
                            model.image.InputStream.CopyTo(target);
                            var resizedImage = new ImageResizer(target.ToArray());
                            resizedImage.Resize(400, 200, false, ImageEncoding.Jpg90);
                            resizedImage.SaveToFile(filePath);
                        }
                        else
                        {
                            model.image.SaveAs(filePath);
                        }
                    }
                    WebSecurity.CreateUserAndAccount(
                        model.UserName,
                        model.Password,
                        new
                    {
                        username = model.UserName,
                        password = model.Password,
                        name     = model.name,
                        //email = model.email,
                        status       = model.status,
                        superUser    = model.superUser,
                        activeKey    = "",
                        companyID    = db.Users.Find(WebSecurity.CurrentUserId).companyID,
                        departmentID = model.department_id,
                        createUser   = WebSecurity.CurrentUserId,
                        positionID   = model.position_id,
                        imageUrl     = (model.image != null) ? imageUrl : null
                    });
                    var roleProvider = (SimpleRoleProvider)Roles.Provider;
                    roleProvider.AddUsersToRoles(new[] { model.UserName }, model.roles);
                    //ViewBag.roles = new MultiSelectList(db.Webpages_Roles.ToList(), "RoleName", "RoleName");
                    //ViewBag.department_id = new SelectList(db.Departments.Where(dep => dep.companyID == companyID), "ID", "name", model.department_id);
                    //ViewBag.position_id = new SelectList(db.Positions.Where(dep => dep.companyID == companyID), "ID", "name", model.position_id);
                    //ViewBag.Done = "Usuario registrado satisfactoriamente";
                    return(RedirectToAction("Index", "Users"));
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }
            ViewBag.roles         = new MultiSelectList(db.Webpages_Roles.ToList(), "RoleName", "RoleName");
            ViewBag.department_id = new SelectList(db.Departments.Where(dep => dep.companyID == companyID), "ID", "name", model.department_id);
            ViewBag.position_id   = new SelectList(db.Positions.Where(dep => dep.companyID == companyID), "ID", "name", model.position_id);

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 10
0
        public ActionResult EditAccount(EditAccountModel model, bool adminUser)
        {
            if (ModelState.IsValid)
            {
                var    imageGUID = Guid.NewGuid();
                string imageUrl  = "";
                if (model.image != null)
                {
                    imageUrl = imageGUID +
                               Path.GetExtension(model.image.FileName);
                    string filePath = Path.Combine(
                        Server.MapPath("~/Uploads/UserImages"),
                        imageGUID + Path.GetExtension(model.image.FileName
                                                      ));
                    if (model.image.ContentLength > 102400)
                    {
                        MemoryStream target = new MemoryStream();
                        model.image.InputStream.CopyTo(target);
                        var resizedImage = new ImageResizer(target.ToArray());
                        resizedImage.Resize(400, 200, false, ImageEncoding.Jpg90);
                        resizedImage.SaveToFile(filePath);
                    }
                    else
                    {
                        model.image.SaveAs(filePath);
                    }

                    var      images = Directory.GetFiles(Server.MapPath("~/Uploads/UserImages"));
                    FileInfo old    = new FileInfo(Server.MapPath("~/Uploads/UserImages") + "\\" + model.imageUrl);
                    if (images.Contains(old.FullName))
                    {
                        filePath = model.image.FileName;
                        System.IO.File.Delete(Path.Combine(Server.MapPath("~/Uploads/UserImages"), model.imageUrl));
                        model.imageUrl = filePath;
                    }
                    model.imageUrl = imageUrl;
                }
                else if (model.image == null && model.imageUrl != null)
                {
                    var      images = Directory.GetFiles(Server.MapPath("~/Uploads/UserImages"));
                    FileInfo old    = new FileInfo(Server.MapPath("~/Uploads/UserImages") + "\\" + model.imageUrl);
                    if (images.Contains(old.FullName))
                    {
                        System.IO.File.Delete(Path.Combine(Server.MapPath("~/Uploads/UserImages"), model.imageUrl));
                        model.imageUrl = "";
                    }
                }

                if (adminUser && model.userID == WebSecurity.CurrentUserId)
                {
                    model.position_id   = null;
                    model.department_id = null;
                }
                User usr = db.Users.Find(model.userID);
                usr.name     = model.name;
                usr.password = model.Password;
                usr.username = model.UserName;
                usr.imageUrl = model.imageUrl;
                if (adminUser)
                {
                    usr.departmentID = model.department_id;
                    usr.positionID   = model.position_id;
                    usr.status       = Convert.ToInt32(model.activeUser);
                    usr.Webpages_Roles.Clear();
                    db.Entry(usr).State = EntityState.Modified;
                    db.SaveChanges();
                    var roleProvider = (SimpleRoleProvider)Roles.Provider;
                    if (model.roles != null)
                    {
                        roleProvider.AddUsersToRoles(new[] { model.UserName }, model.roles);
                    }
                    return(RedirectToAction("Index", "Home", null));
                }
            }
            User currentUser = db.Users.Find(WebSecurity.CurrentUserId);
            int? companyID   = currentUser.companyID;

            ViewBag.department_id = new SelectList(db.Departments.Where(dep => dep.companyID == companyID), "ID", "name", model.department_id);
            ViewBag.position_id   = new SelectList(db.Positions.Where(dep => dep.companyID == companyID), "ID", "name", model.position_id);
            ViewBag.roles         = new MultiSelectList(db.Webpages_Roles, "RoleName", "RoleName", model.roles);
            ViewBag.adminUser     = (currentUser.superUser) ? true : false;

            return(View(model));
        }
Ejemplo n.º 11
0
        public ActionResult Create(CompanyViewModel company, int[] rulesCompany, HttpPostedFileBase logoImage)
        {
            if (ModelState.IsValid)
            {
                company.status = false;

                var imageGUID = Guid.NewGuid();
                if (logoImage != null)
                {
                    string imageUrl = imageGUID +
                                      Path.GetExtension(logoImage.FileName);
                    string filePath = Path.Combine(
                        Server.MapPath("~/Uploads/CompanyLogos"),
                        imageGUID + Path.GetExtension(logoImage.FileName
                                                      ));
                    if (logoImage.ContentLength > 102400)
                    {
                        MemoryStream target = new MemoryStream();
                        logoImage.InputStream.CopyTo(target);
                        var resizedImage = new ImageResizer(target.ToArray());
                        resizedImage.Resize(400, 200, false, ImageEncoding.Jpg90);
                        resizedImage.SaveToFile(filePath);
                    }
                    else
                    {
                        logoImage.SaveAs(filePath);
                    }
                }

                Company realCompany = new Company();
                realCompany.name        = company.name;
                realCompany.companyText = company.companyText;
                realCompany.description = company.description;
                realCompany.email       = company.email;
                if (logoImage != null)
                {
                    realCompany.logo = imageGUID + Path.GetExtension(logoImage.FileName);
                }
                else
                {
                    realCompany.logo = "";
                }

                realCompany.status = company.status;
                if (rulesCompany != null)
                {
                    foreach (int r in rulesCompany)
                    {
                        var rule = db.Rules.Find(r);
                        realCompany.Rules.Add(rule);
                        rule.Companies.Add(realCompany);
                    }
                }

                db.Companies.Add(realCompany);

                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.rulesCompany = db.Rules.ToSelectListItems(r => r.code + " - " + r.name, r => r.ID.ToString());

            return(View(company));
        }
Ejemplo n.º 12
0
        public ActionResult Edit(CompanyViewModel company, HttpPostedFileBase logoImage)
        {
            if (ModelState.IsValid)
            {
                Company comp = db.Companies.Include(c => c.Rules).FirstOrDefault(c => c.ID == company.ID);
                comp.Rules.Clear();

                db.Entry(comp).State = EntityState.Modified;

                var imageGUID = Guid.NewGuid();
                if (logoImage != null)
                {
                    string imageUrl = imageGUID +
                                      Path.GetExtension(logoImage.FileName);
                    string filePath = Path.Combine(
                        Server.MapPath("~/Uploads/CompanyLogos"),
                        imageGUID + Path.GetExtension(logoImage.FileName
                                                      ));

                    if (logoImage.ContentLength > 102400)
                    {
                        MemoryStream target = new MemoryStream();
                        logoImage.InputStream.CopyTo(target);
                        var resizedImage = new ImageResizer(target.ToArray());
                        resizedImage.Resize(400, 200, false, ImageEncoding.Jpg90);
                        resizedImage.SaveToFile(filePath);
                    }
                    else
                    {
                        logoImage.SaveAs(filePath);
                    }

                    var      images = Directory.GetFiles(Server.MapPath("~/Uploads/CompanyLogos"));
                    FileInfo old    = new FileInfo(Server.MapPath("~/Uploads/CompanyLogos") + "\\" + company.logo);
                    if (images.Contains(old.FullName))
                    {
                        filePath = logoImage.FileName;
                        System.IO.File.Delete(Path.Combine(Server.MapPath("~/Uploads/CompanyLogos"), company.logo));
                        company.logo = filePath;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(company.filename))
                    {
                        var      images = Directory.GetFiles(Server.MapPath("~/Uploads/CompanyLogos"));
                        FileInfo old    = new FileInfo(Server.MapPath("~/Uploads/CompanyLogos") + "\\" + company.logo);
                        if (images.Contains(old.FullName))
                        {
                            System.IO.File.Delete(Path.Combine(Server.MapPath("~/Uploads/CompanyLogos"), company.logo));
                            company.logo = "";
                        }
                    }
                }

                comp.name        = company.name;
                comp.companyText = company.companyText;
                comp.description = company.description;
                comp.email       = company.email;

                if (logoImage != null)
                {
                    comp.logo = imageGUID + Path.GetExtension(logoImage.FileName);
                }
                else
                {
                    comp.logo = "";
                }

                comp.status = company.status;
                if (company.rulesCompany != null)
                {
                    foreach (int r in company.rulesCompany)
                    {
                        var rule = db.Rules.Find(r);
                        comp.Rules.Add(rule);
                    }
                }
                db.Entry(comp).State = EntityState.Modified;

                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.rulesCompany = db.Rules.ToSelectListItems(r => r.code + " - " + r.name, r => r.ID.ToString(), rl => company.rulesCompany.Contains(rl.ID));
            return(View(company));
        }