Exemplo n.º 1
0
        public void UploadNow(HttpPostedFileWrapper upload, string folder)
        {
            string nameFolder = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString("00") + DateTime.Now.Day.ToString("00");
            string path       = ValueConstant.IMAGE_PATH + ValueConstant.IMAGE_POST_PATH + nameFolder;
            var    fullPath   = string.Empty;

            if (!Directory.Exists(path))
            {
                fullPath = CreateFolder();
            }
            else
            {
                fullPath = ValueConstant.IMAGE_PATH + ValueConstant.IMAGE_POST_PATH + folder;
            }
            if (upload != null && upload.ContentType.Contains("image"))
            {
                string imageName = upload.FileName;
                string filePath  = Path.Combine(Server.MapPath(fullPath), imageName);
                upload.SaveAs(filePath);
            }
            else
            {
                string fileName = upload.FileName;
                string filePath = Path.Combine(Server.MapPath(fullPath), fileName);
                upload.SaveAs(filePath);
            }
        }
        public ViewResult Icon(HttpPostedFileWrapper icon)
        {
            string path = Path.GetFileName(icon.FileName);

            icon.SaveAs(Path.Combine(Server.MapPath("~/Image/"), path));
            return(View());
        }
Exemplo n.º 3
0
 public ActionResult Index(HttpPostedFileWrapper CustomerFile, HttpPostedFileWrapper ToolFile, HttpPostedFileWrapper RentalFile)
 {
     try
     {
         if (ModelState.IsValid)
         {
             if (CustomerFile != null && CustomerFile.ContentLength > 0 && ToolFile != null && ToolFile.ContentLength > 0 && RentalFile != null && RentalFile.ContentLength > 0)
             {
                 CustomerFile.SaveAs(Server.MapPath("~/DataFiles/Customers.txt"));
                 ToolFile.SaveAs(Server.MapPath("~/DataFiles/Tools.txt"));
                 RentalFile.SaveAs(Server.MapPath("~/DataFiles/Rental_data.txt"));
                 ShowNotification("Success", "DataFiles Saved successfully. Use Other Modules with changed data.", "success");
                 return(View());
             }
             else
             {
                 ShowNotification("Error", "Doesn't upload any file OR Upload Empty File", "warning");
                 return(View());
             }
         }
         return(View());
     }
     catch
     {
         ShowNotification("Error", "Error while saving Files.", "warning");
         return(View());
     }
 }
Exemplo n.º 4
0
        public ActionResult Edit(tb_Prodect model,
                                 HttpPostedFileWrapper Icon,
                                 HttpPostedFileWrapper Conver)
        {
            tb_Prodect pronew       = Entities.tb_Prodect.FirstOrDefault(t => t.Id == model.Id);
            string     pathFileName = string.Empty;

            if (Icon?.ContentLength > 0)
            {
                pathFileName = $"{basePath}{CommonHelper.GetNowLangTime()}1{Path.GetExtension(Icon.FileName)}";
                Icon.SaveAs(Server.MapPath("~" + pathFileName));
                pronew.Icon = pathFileName;
            }

            if (Conver?.ContentLength > 0)
            {
                pathFileName = $"{basePath}{CommonHelper.GetNowLangTime()}2{Path.GetExtension(Conver.FileName)}";
                Conver.SaveAs(Server.MapPath("~" + pathFileName));
                pronew.Conver = pathFileName;
            }
            pronew.Title      = model.Title;
            pronew.Content    = model.Content;
            pronew.LanguageId = Language.Id;
            pronew.NormsId    = model.NormsId;

            Entities.SaveChanges();
            return(RedirectToAction("List"));
        }
Exemplo n.º 5
0
        public ActionResult UpdateProfile(string id, Patient model, HttpPostedFileWrapper picture)
        {
            var patient = db.Patients.Single(c => c.ApplicationUserId == id);

            if (picture != null)
            {
                var path = Path.Combine(Server.MapPath("~/Content/img"), picture.FileName);
                picture.SaveAs(path);
                patient.Image = picture.FileName;
            }
            patient.FirstName        = model.FirstName;
            patient.LastName         = model.LastName;
            patient.FullName         = model.FirstName + " " + model.LastName;
            patient.Contact          = model.Contact;
            patient.Address          = model.Address;
            patient.LevelOfEducation = model.LevelOfEducation;
            patient.Age           = model.Age;
            patient.MaritalStatus = model.MaritalStatus;
            patient.Language      = model.Language;
            patient.Gender        = model.Gender;
            patient.PhoneNo       = model.PhoneNo;
            db.SaveChanges();
            string audiuserName = User.Identity.GetUserName();

            AuditExtension.AddAudit(audiuserName, "Updated Patient Details", "Patients");
            return(RedirectToAction("Index"));
        }
Exemplo n.º 6
0
 public ActionResult Add(ContestantDTO contestant, HttpPostedFileWrapper PhotoUrl)
 {
     try
     {
         Contestant newcontestant = Mapper.Map <Contestant>(contestant);
         // Verify that the user selected a file
         if (PhotoUrl != null && PhotoUrl.ContentLength > 0)
         {
             // extract only the filename
             var fileName = Path.GetFileName(PhotoUrl.FileName);
             // store the file inside /Images/Photos folder
             var path = Path.Combine(Server.MapPath("~/Images/Photos"), fileName);
             PhotoUrl.SaveAs(path);
             newcontestant.PhotoUrl = fileName;
         }
         unitOfWork.Contestant.Add(newcontestant);
         unitOfWork.Complete();
     }
     catch (Exception e)
     {
         TempData["Message"]     = "Contestant adding failed !";
         TempData["MessageType"] = "danger";
         return(RedirectToAction("Index"));
     }
     TempData["Message"]     = "Contestant added successfully !";
     TempData["MessageType"] = "success";
     return(RedirectToAction("Index"));
 }
Exemplo n.º 7
0
        public ActionResult Upload(string qqfile)
        {
            var postedFile                  = System.Web.HttpContext.Current.Request.Files[0];
            HttpPostedFileBase file         = new HttpPostedFileWrapper(postedFile);
            string             nodeRecordId = Guid.NewGuid().ToString();

            JpmSoftDAL.Message gpp = new JpmSoftDAL.Message();
            gpp.Message_ID   = Guid.NewGuid().ToString();
            gpp.Message_Name = nodeRecordId;
            if (file == null || file.ContentLength == 0)
            {
                return(Json(new
                {
                    bRet = false,
                    sMsg = "请选择文件!"
                }, "text/xml"));
            }
            var    nfname    = Guid.NewGuid().ToString();
            string aLastName = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1, (file.FileName.Length - file.FileName.LastIndexOf(".") - 1)); //扩展名
            string name      = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1);                                                             // 字符串截取函数取得文件名
            string path      = nfname + "." + aLastName;

            gpp.Message_Name = name;
            Session["gpp"]   = gpp;
            string sPath = Server.MapPath(@"~\Content\UploadFile\Annex\");      // 物理文件夹路径

            if (!System.IO.Directory.Exists(sPath))
            {
                System.IO.Directory.CreateDirectory(sPath);
            }
            file.SaveAs(Server.MapPath(@"~\Content\UploadFile\Annex\" + path));
            return(Json(new { success = true, fileName = qqfile, nfilename = path, msg = "上传成功。" }, "text/xml"));
        }
Exemplo n.º 8
0
        public WrappedJsonResult UploadImage(HttpPostedFileWrapper ImageFile)
        {
            if (ImageFile == null || ImageFile.ContentLength == 0)
            {
                return(new WrappedJsonResult
                {
                    Data = new
                    {
                        IsValid = false,
                        Message = "Не удалось загрузить изображение",
                        ImagePath = string.Empty
                    }
                });
            }

            var fileName  = String.Format("{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(ImageFile.FileName));
            var imagePath = Path.Combine(LocalPath.AbsoluteUploadsDirectory, fileName);

            ImageFile.SaveAs(imagePath);

            return(new WrappedJsonResult
            {
                Data = new
                {
                    IsValid = true,
                    Message = string.Empty,
                    ImagePath = Url.Content("~/" + Path.Combine(LocalPath.RelativeUploadsDirectory, fileName))
                }
            });
        }
Exemplo n.º 9
0
        public Author Register(Author author, HttpPostedFileWrapper file)
        {
            try
            {
                if (file != null)
                {
                    if (IsImage(file.ContentType))
                    {
                        var imageName         = Path.GetFileName(file?.FileName);
                        var formattedImgTitle = $"{author.Name}-{author.Surname}-{imageName}";

                        var imagesPath = Path.Combine(HttpContext.Current.Server.MapPath("~/Images/Authors/"), formattedImgTitle);
                        file.SaveAs(imagesPath);

                        author.ProfileImage = formattedImgTitle;
                    }
                }

                author.Password = _securirtyService.Encrypt(author.Password);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            _topBloggersDb.Authors.Add(author);
            _topBloggersDb.SaveChanges();

            return(author);
        }
Exemplo n.º 10
0
        public WrappedJsonResult UploadFoto(HttpPostedFileWrapper file)
        {
            try
            {
                if (file == null || file.ContentLength == 0)
                {
                    return(new WrappedJsonResult
                    {
                        Data = new
                        {
                            IsValid = false,
                            Message = Rp3.AgendaComercial.Resources.MessageFor.NoPudoCargarFoto,
                            ImagePath = string.Empty
                        }
                    });
                }

                if (file.ContentLength > Constantes.ProfileFotosSize.MaxSizeUploadFile)
                {
                    return(new WrappedJsonResult
                    {
                        Data = new
                        {
                            IsValid = false,
                            Message = String.Format(Rp3.AgendaComercial.Resources.MessageFor.TamanoFotoExcedido, (Constantes.ProfileFotosSize.MaxSizeUploadFile / 1048576)),
                            ImagePath = string.Empty
                        }
                    });
                }

                var fileName  = String.Format("{0}{1}", Guid.NewGuid(), System.IO.Path.GetExtension(file.FileName));
                var imagePath = Path.Combine(Server.MapPath(Url.Content(Constantes.ProductoMedia.FilePath)), fileName);

                file.SaveAs(imagePath);
                //SaveThumbnail(imagePath);

                return(new WrappedJsonResult
                {
                    Data = new
                    {
                        IsValid = true,
                        Message = Rp3.AgendaComercial.Resources.MessageFor.ArchivoSubidoCorrectamente,
                        ImagePath = Url.Content(Constantes.ProductoMedia.FileSavePath + fileName),
                        Width = Constantes.ProfileFotosSize.ProfilePictureWidth,
                        Height = Constantes.ProfileFotosSize.ProfilePictureHeight
                    }
                });
            }
            catch
            {
                return(new WrappedJsonResult
                {
                    Data = new
                    {
                        IsValid = false,
                        Message = Rp3.AgendaComercial.Resources.MessageFor.NoPudoCargarArchivo
                    }
                });
            }
        }
Exemplo n.º 11
0
        public ActionResult Edit(tb_Applocation model, HttpPostedFileWrapper ImgAddress, HttpPostedFileWrapper Conver)
        {
            tb_Applocation appnew = Entities.tb_Applocation.FirstOrDefault(t => t.Id == model.Id);

            if (ImgAddress?.ContentLength > 0)
            {
                string fileName = $"/ImgProject/{Common.CommonHelper.GetNowLangTime()}1{Path.GetExtension(ImgAddress.FileName)}";
                ImgAddress.SaveAs(Server.MapPath(fileName));
                appnew.ImgAddress = fileName;
            }

            if (Conver?.ContentLength > 0)
            {
                string fileName = $"/ImgProject/{Common.CommonHelper.GetNowLangTime()}2{Path.GetExtension(Conver.FileName)}";
                Conver.SaveAs(Server.MapPath(fileName));
                appnew.Conver = fileName;
            }

            appnew.LanguageId = Language.Id;
            appnew.AppName    = model.AppName;
            appnew.CreateTime = DateTime.Now;

            Entities.SaveChanges();
            return(View(appnew));
        }
Exemplo n.º 12
0
        public static string SaveFile(HttpPostedFileWrapper file, string filePath)
        {
            var strPath = HttpContext.Current.Server.MapPath(filePath);

            file.SaveAs(strPath);
            return(strPath);
        }
Exemplo n.º 13
0
        public ActionResult SaveProfileImage()
        {
            try
            {
                if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
                    HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic);
                    var    fileName             = Path.GetFileName(filebase.FileName);
                    string fileExtension        = Path.GetExtension(fileName);
                    var    path = string.Empty;
                    if (fileExtension == ".pdf" || fileExtension == ".jpg" || fileExtension == ".jpeg")
                    {
                        //path = Path.Combine(Server.MapPath("~/TempImageUpload/"), DateTime.Now.ToString().Replace(' ', '_').Replace(':', '_').Replace('-', '_') + "_" + fileName);

                        path = @"D:\RBSMEWEB\TempImageUpload\" + DateTime.Now.ToString().Replace(' ', '_').Replace(':', '_').Replace('-', '_').Replace('\\', '_').Replace('/', '_') + "_" + fileName;
                        filebase.SaveAs(path);
                    }
                    else
                    {
                        return(Json("Wrong file format given"));
                    }


                    return(Json(path));
                }
                else
                {
                    return(Json("No File Saved."));
                }
            }
            catch (Exception ex) {
                return(Json("Error While Saving."));
            }
        }
Exemplo n.º 14
0
        public ActionResult ImportCsv(HttpPostedFileWrapper uploadFile)
        {
            string fileName = Guid.NewGuid().ToString("N").Substring(0, 10);

            if (uploadFile != null)
            {
                uploadFile.SaveAs(Server.MapPath("~/tmp/importTmp.csv"));
            }

            List <string> row = null;
            var           sql = new SqlClass();

            using (var csv = new CsvReader(Server.MapPath("~/tmp/importTmp.csv")))
            {
                while ((row = csv.ReadRow()) != null)
                {
                    if (sql.IsCheckUserID(row[1]) == false)
                    {
                        sql.AddUserData(row[1], row[2], row[3], row[4], row[5]);
                    }
                }
            }


            return(RedirectToAction("List", "Home"));
        }
        private Resultado SaveFile(HttpPostedFileWrapper file, string subfolder)
        {
            try
            {
                string ImageName = System.IO.Path.GetFileNameWithoutExtension(file.FileName);
                ImageName += "_" + DateTime.Now.ToString("dd-MM-yyyy hh_mm_ss", CultureInfo.InvariantCulture);
                ImageName += System.IO.Path.GetExtension(file.FileName);
                ImageName  = subfolder + ImageName;
                string physicalPath = Server.MapPath("~");

                Directory.CreateDirectory(physicalPath);

                physicalPath += ImageName;

                // save image in folder
                file.SaveAs(physicalPath);
                return(new Resultado()
                {
                    Status = true, Message = ImageName
                });
            }
            catch (Exception exception)
            {
                return(new Resultado()
                {
                    Status = false, Message = exception.Message
                });
            }
        }
Exemplo n.º 16
0
        public ActionResult Add(tb_Picture model, HttpPostedFileWrapper picture)
        {
            List <string> filenames = new List <string>();

            foreach (string key in Request.Files.Keys)
            {
                HttpPostedFileWrapper pid = Request.Files[key] as HttpPostedFileWrapper;
                if (pid.ContentLength > 0)
                {
                    string fileName = basePath + Common.CommonHelper.GetNowLangTime() + key + Path.GetExtension(pid.FileName);
                    pid.SaveAs(Server.MapPath("~" + fileName));
                    filenames.Add(fileName);
                }
            }
            model.Path = String.Join(",", filenames);
            if (model.PicTypeId == 2)
            {
                model.LanguageId = Language.Id;
            }

            Entities.tb_Picture.Add(model);
            Entities.SaveChanges();

            return(RedirectToAction("List", new { picSort = 2 }));
        }
Exemplo n.º 17
0
        public string UpLoadFile(string fileName, string path)
        {
            //上传和返回(保存到数据库中)的路径
            var uppath   = string.Empty;
            var savepath = string.Empty;

            if (HttpContext.Current.Request.Files.Count > 0)
            {
                //HttpContext.Current.Request.Files[""];
                HttpPostedFileBase imgFile = new HttpPostedFileWrapper(HttpContext.Current.Request.Files[fileName]);
                if (imgFile != null)
                {
                    //创建图片新的名称
                    var nameImg = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    //获得上传图片的路径
                    var strPath = imgFile.FileName;
                    //获得上传图片的类型(后缀名)
                    var type = strPath.Substring(strPath.LastIndexOf(".") + 1).ToLower();
                    if (type != "rar" && type != "zip")
                    {
                        return(savepath);
                    }
                    //拼写数据库保存的相对路径字符串
                    uppath    = string.IsNullOrEmpty(path) ? HttpContext.Current.Server.MapPath("~/Uploads/") : HttpContext.Current.Server.MapPath("~/Uploads/" + path + "/");
                    savepath += nameImg + "." + type;
                    //拼写上传的路径
                    uppath += nameImg + "." + type;
                    //上传图片
                    imgFile.SaveAs(uppath);
                    return(savepath);
                }
            }
            return("");
        }
        public ActionResult SetFile(tb_File model, HttpPostedFileWrapper file)
        {
            if (file != null && file.ContentLength > 0)
            {
                string path = $"/Files/{Guid.NewGuid()}_{file.FileName}";
                file.SaveAs(Server.MapPath("~" + path));
                model.Path = path;
            }

            if (model.Id == 0)
            {
                entities.tb_File.Add(model);
            }
            else
            {
                entities.Entry(model).State = System.Data.Entity.EntityState.Modified;
                if (model.Path == null)
                {
                    entities.Entry(model).Property(x => x.Path).IsModified = false;
                }
            }

            entities.SaveChanges();

            return(RedirectToAction("List"));
        }
Exemplo n.º 19
0
 public ActionResult SaveImage(string description, string name)
 {
     try
     {
         if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
         {
             var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
             HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic);
             // var fileName = Path.GetFileName(filebase.FileName);
             var fileName = Guid.NewGuid().ToString() + Path.GetExtension(filebase.FileName);
             var path     = Path.Combine(Server.MapPath("~/Images"), fileName);
             filebase.SaveAs(path);
             //var db = new GalleryContext();
             db.Photos.Add(new Photo {
                 Name = name, Description = description, Path = path
             });
             db.SaveChanges();
             return(Json("Photo was saved."));
         }
         else
         {
             return(Json("No File Saved."));
         }
     }
     catch (Exception ex) { return(Json("Error While Saving.")); }
 }
        public ActionResult Index(HttpPostedFileWrapper file, string content)
        {
            string imgname = Guid.NewGuid().ToString() + ".jpg";
            string imgpath = Server.MapPath("~/upload/image/" + imgname);

            file.SaveAs(imgpath);
            CompanyProfile pro = client.FindOne <CompanyProfile>(new { Language = Language });

            if (pro == null)
            {
                pro          = new CompanyProfile();
                pro.ImaPath  = "/upload/image/" + imgname;
                pro.Content  = content;
                pro.Language = Language;
                pro.Type     = ContentTypeEnum.公司简介;
                client.InsertOne(pro);
            }
            else
            {
                pro.ImaPath  = "/upload/image/" + imgname;
                pro.Content  = content;
                pro.Language = Language;
                pro.Type     = ContentTypeEnum.公司简介;
                client.UpdateOneById(pro);
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 21
0
        /// <summary>
        /// 上传图片.
        /// </summary>
        /// <returns>Json.</returns>
        public ActionResult UploadPic()
        {
            string photoPath           = string.Empty;
            string photoName           = string.Empty;
            string msg                 = string.Empty;
            HttpPostedFileWrapper file = (HttpPostedFileWrapper)Request.Files[0];

            photoName = file.FileName;
            if (string.IsNullOrEmpty(photoName))
            {
                msg = "无效文件,请重新上传!";
                return(Json(new { photoPath, msg, code = 400, photoName = string.Empty }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                // 获得当前时间的string类型
                string name       = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
                string path       = "/Source/headPhoto/";
                string uploadPath = Server.MapPath("~/" + path);
                string ext        = Path.GetExtension(photoName);
                string savePath   = uploadPath + name + ext;
                file.SaveAs(savePath);
                photoPath = path + name + ext;
                msg       = "上传成功!";
                return(Json(new { photoPath, msg, code = 200, photoName }, JsonRequestBehavior.AllowGet));
            }
        }
Exemplo n.º 22
0
        // Builders
        protected Guid AddMediaLibraryFileInternal(HttpPostedFileWrapper file, string uploadDirectory, string libraryFolderPath = null, bool checkPermisions = false)
        {
            if (file is null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            if (!AppConfig.AllowedImageExtensions.Contains(Path.GetExtension(file.FileName)))
            {
                throw new InvalidOperationException("The app is not configured to allow this type of image.");
            }

            EnsureDirectory(uploadDirectory);
            var(name, extension) = GetNameAndExtension(file.FileName);
            var uploadFilePath = GetNonCollidingFilePath(uploadDirectory, name, extension);

            file.SaveAs(uploadFilePath);

            try
            {
                return(MediaLibraryRepository.AddMediaLibraryFile(uploadFilePath, libraryFolderPath, checkPermisions));
            }
            finally
            {
                CMS.IO.File.Delete(uploadFilePath);
            }
        }
Exemplo n.º 23
0
 public ActionResult Update(int id, ContestantDTO contestant, HttpPostedFileWrapper PhotoUrl)
 {
     try
     {
         Contestant updcontestant    = unitOfWork.Contestant.Get(id);
         string     previousPhotoUrl = updcontestant.PhotoUrl;
         Mapper.Map(contestant, updcontestant);
         // Verify that the user selected a file
         if (PhotoUrl != null && PhotoUrl.ContentLength > 0)
         {
             // extract only the filename
             var fileName = Path.GetFileName(PhotoUrl.FileName);
             // store the file inside /Images/Photos folder
             var path = Path.Combine(Server.MapPath("~/Images/Photos"), fileName);
             PhotoUrl.SaveAs(path);
             updcontestant.PhotoUrl = fileName;
         }
         else
         {
             updcontestant.PhotoUrl = previousPhotoUrl;
         }
         unitOfWork.Contestant.Update(updcontestant);
         unitOfWork.Complete();
     }
     catch (Exception e)
     {
         TempData["Message"]     = "Contestant updating failed !";
         TempData["MessageType"] = "danger";
         return(RedirectToAction("Index"));
     }
     TempData["Message"]     = "Contestant updated successfully !";
     TempData["MessageType"] = "success";
     return(RedirectToAction("Index"));
 }
Exemplo n.º 24
0
        public async Task <ActionResult> CreateBook(HttpPostedFileWrapper book)
        {
            book.SaveAs(Server.MapPath($"/BookFiles/{book.FileName}"));
            await _bookService.CreateBook(Server.MapPath($"/BookFiles/{book.FileName}"));

            return(Redirect("/Home/Index"));
        }
Exemplo n.º 25
0
        public ActionResult File(HttpPostedFileWrapper file)
        {
            file.SaveAs(Path.Combine(Server.MapPath("/images"), Path.GetFileName(file.FileName)));//用Server.MapPath获得相对路径的物理路径
            return(Json("上传成功"));

            //string  filePath = Path.Combine(HttpContext.Server.MapPath("../images"),Path.GetFileName(file.FileName));
            //file.SaveAs(filePath);
            //return Json("上传成功");

            //HttpPostedFileBase f = Request.Files["file"];//最简单的获取方法
            //f.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "/Image/" + f.FileName);//保存图片

            ////这下面是返回json给前端
            //var data1 = new
            //{
            //    src = AppDomain.CurrentDomain.BaseDirectory + "/Image/" + f.FileName,//服务器储存路径
            //};
            //var Person = new
            //{
            //    code = 0,//0表示成功
            //    msg = "",//这个是失败返回的错误
            //    data = data1
            //};
            //return Json(Person);//格式化为json
        }
Exemplo n.º 26
0
        public JsonResult UploadImage(HttpPostedFileWrapper upload)
        {
            if (upload != null)
            {
                string ImageName = upload.FileName;

                // Se obtiene el path de imagenes de Posts.
                var pathPostImages = ConfigurationManager.AppSettings["PathPostImages"];

                // Se obtiene el nombre del usuario actual para acceder al directorio de imagenes de posts de ese usuario.
                var currentUserName = User.Identity.GetUserName();
                var directory       = pathPostImages + currentUserName + "\\";

                // Se crea el directorio; si ya existe el directorio, la función no hace nada.
                directory = Server.MapPath(directory);
                Directory.CreateDirectory(directory);

                // Se obtiene el path final de la imagen.
                string path = System.IO.Path.Combine(directory, ImageName);

                // Se guarda la imagen.
                upload.SaveAs(path);

                var result = new
                {
                    Resultado = "imagen enviada correctamente."
                };

                return(Json(result, JsonRequestBehavior.AllowGet));
            }

            return(Json(null, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 27
0
 public JsonResult UploadImageCkeditor(int key, HttpPostedFileWrapper upload)
 {
     try
     {
         var userPath = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/{3}/", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.pictureNews, DateTime.Now.ToString("dd-MM-yyyy"), SysBaseInfor.GetCurrentUserId()));
         if (!Directory.Exists(userPath))
         {
             Directory.CreateDirectory(userPath);
         }
         if (upload != null)
         {
             string imgType  = "";
             var    isImages = upload.InputStream.IsImage(out imgType);
             if (isImages && !string.IsNullOrEmpty(imgType))
             {
                 string ImageName = Guid.NewGuid().ToString() + "." + imgType;
                 string path      = Path.Combine(userPath, ImageName);
                 upload.SaveAs(path);
                 var uriImage = string.Format("/UserImages/{0}/{1}/{2}/{3}/{4}", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.pictureNews, DateTime.Now.ToString("dd-MM-yyyy"), SysBaseInfor.GetCurrentUserId(), ImageName);
                 return(Json(uriImage));
             }
             return(Json("Chỉ được tải lên file hình ảnh!"));
         }
         ;
         return(Json("Không tìm thấy file!"));
     }
     catch (Exception ex)
     {
         return(Json("Có lỗi xảy ra. Xin vui lòng thử lại!"));
     }
 }
Exemplo n.º 28
0
        public JsonResult UploadFileCkeditor(int key, HttpPostedFileWrapper upload)
        {
            try
            {
                var userPath = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/{3}/", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.newsAttachment, DateTime.Now.ToString("dd-MM-yyyy"), SysBaseInfor.GetCurrentUserId()));
                if (!Directory.Exists(userPath))
                {
                    Directory.CreateDirectory(userPath);
                }

                if (upload != null)
                {
                    string fileName = Guid.NewGuid().ToString() + "_" + upload.FileName;
                    if (Array.IndexOf(listDocExtension, Path.GetExtension(fileName)) > -1)
                    {
                        string path = Path.Combine(userPath, fileName);
                        upload.SaveAs(path);
                        var uriFile = string.Format("/UserImages/{0}/{1}/{2}/{3}/{4}", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.newsAttachment, DateTime.Now.ToString("dd-MM-yyyy"), SysBaseInfor.GetCurrentUserId(), fileName);
                        return(Json(uriFile));
                    }
                    return(Json("Chỉ được tải lên file word,excel,pdf hoặc file nén zip,rar"));
                }
                ;
                return(Json("Không tìm thấy file!"));
            }
            catch (Exception ex)
            {
                return(Json("Có lỗi xảy ra!"));
            }
        }
        public ActionResult Create([DataSourceRequest] DataSourceRequest request, Partner partner)
        {
            if (ModelState.IsValid)
            {
                if (TempData["File"] != null)
                {
                    string fileName = "";
                    //Save Partner's Logo
                    HttpPostedFileWrapper file = TempData["File"] as HttpPostedFileWrapper;
                    if (file != null)
                    {
                        string path = Server.MapPath("~/Content/Images/PromotionPartners/");
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        fileName = file.FileName;
                        file.SaveAs(path + Path.GetFileName(file.FileName));
                    }
                    partner.PartnerLogo = "Images/PromotionPartners/" + fileName;
                }

                db.Partners.Add(partner);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(RedirectToAction("Index"));
        }
Exemplo n.º 30
0
        public ActionResult Finish(KPI model, HttpPostedFileWrapper upload)
        {
            model.id = model.id > 0 ? -model.id : model.id;
            if (ModelState.IsValid)
            {
                using (var scope = new TransactionScope())
                {
                    var user = User.Identity.Name.Split('@')[0];
                    var KPI  = db.KPIs.Find(model.id);
                    if (KPI.Email != user && KPI.KP1.Email != user)
                    {
                        return(HttpNotFound());
                    }
                    KPI.KetQua          = model.KetQua;
                    KPI.GhiChu2         = model.GhiChu2;
                    KPI.Filename        = upload?.FileName;
                    db.Entry(KPI).State = EntityState.Modified;

                    LogInfo(model);
                    db.SaveChanges();

                    if (upload != null)
                    {
                        upload.SaveAs(Server.MapPath("~/App_Data/") + -model.id);
                    }

                    scope.Complete();
                    return(RedirectToAction("Details", new { id = -KPI.idKPI }));
                }
            }

            ViewBag.Names = db.KpiUsers.First().Names;
            return(View(db.KPIs.Find(model.id)));
        }