Example #1
0
 public ActionResult edit(Employees emp, HttpPostedFileBase Picture, HttpPostedFileBase Attachment, string Level)
 {
     if(ModelState.IsValid)
     {
         try
         {
             if (Picture != null)
             {
                 var path = Path.Combine(Server.MapPath("~/Content/Images/Admin"), emp.Email + ".png");
                 Picture.SaveAs(path);
                 emp.Picture = "Y";
             }
             if (Attachment != null)
             {
                 var path = Path.Combine(Server.MapPath("~/Content/Images/Admin"), emp.Email + Path.GetExtension(Attachment.FileName));
                 Picture.SaveAs(path);
                 emp.Attachment = "Y";
             }
             repository.SaveEmployee(emp, Level);
         }
         catch (RuleException ex)
         {
             ex.CopyToModelState(ModelState);
         }
     }
     if(ModelState.IsValid)
     {
         return RedirectToAction("index");
     }
     return View();
 }
        public ActionResult TagListEditor_Post(HttpPostedFileBase fileupload)
        {
            OleDbDataAdapter _odbAdapter = new OleDbDataAdapter();
            DataTable _dtable = new DataTable();

            if (fileupload != null && fileupload.ContentLength > 0)
            {
                string _filename = Path.GetFileName(fileupload.FileName);
                string _fileExtension = Path.GetExtension(fileupload.FileName);
                string _path = Path.Combine(Server.MapPath("~/App_Data"), _filename);
                string _newFile = Path.Combine(Server.MapPath("~/App_Data"), _filename.Replace(_fileExtension,".txt"));

                if (_fileExtension == ".rs")
                {
                    fileupload.SaveAs(_path); fileupload.SaveAs(_newFile);

                    Recordset _recordset = new Recordset();

                    _recordset.Open(_path);

                    _odbAdapter.Fill(_dtable, _recordset);

                    _dtable.Columns.Add("Actions",typeof(string));

                    //foreach (DataRow dt in _dtable.Rows)
                    //{
                    //    dt["Actions"] = "";
                    //}
                    //_dtable.AcceptChanges();

                    StreamWriter _sWriter = new StreamWriter(_newFile, false);

                    foreach (DataRow drow in _dtable.Rows)
                    {
                        for (int i = 0; i < _dtable.Columns.Count; i++)
                        {
                            if (!Convert.IsDBNull(drow[i]))
                            {
                                if (i == 1)
                                {
                                    _sWriter.Write("|" + drow[i].ToString());
                                }
                                else
                                {
                                    _sWriter.Write(drow[i].ToString());
                                }

                            }
                        }
                        _sWriter.Write(_sWriter.NewLine);
                    }
                    _sWriter.Close();
                }
            }

            return View(_dtable);
        }
Example #3
0
        public string FileUpload(HttpPostedFileBase fileBase, IList<ResizeImg> imgList, string folder, string fileName)
        {
            if (fileBase == null && !(fileBase.ContentLength > 0)) return "";

            string extension = Path.GetExtension(fileBase.FileName).ToLower();

            if (string.IsNullOrEmpty(extension)) return "";

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = Guid.NewGuid().ToString() + extension;
            }

            string[] modelingExt = { ".stl", ".obj" };

            string saveDir = string.Empty;

            if (modelingExt.Contains(extension))
            {
                saveDir = saveFilePath + folder + Path.DirectorySeparatorChar;
            }
            else
            {
                saveDir = saveFilePath + folder + Path.DirectorySeparatorChar + "backup" + Path.DirectorySeparatorChar;
            }

            if (fileHelper.FilePathCreater(saveDir))
            {
                fileBase.SaveAs(Path.GetFullPath(saveDir + fileName));
            }

            if (folder == "Banner")
            {
                saveDir = saveFilePath + folder + Path.DirectorySeparatorChar + "fullsize" + Path.DirectorySeparatorChar;

                if (fileHelper.FilePathCreater(saveDir))
                {
                    fileBase.SaveAs(Path.GetFullPath(saveDir + fileName));
                }
            }

            if (imgList != null && imgList.Count > 0)
            {
                foreach (var image in imgList)
                {
                    ResizeImage(fileBase, image.width, image.height, fileName, image.folder);
                }
            }

            return fileName;
        }
Example #4
0
        public ActionResult Guncelle(Urunler urun, System.Web.HttpPostedFileBase urunresim)
        {
            string dosyaYolu = "";
            var    mevcut    = db.Urunler.Find(urun.UrunID);

            mevcut.UrunName       = urun.UrunName;
            mevcut.UrunFiyat      = Convert.ToInt32(urun.UrunFiyat);
            mevcut.UrunAciklama   = urun.UrunAciklama;
            mevcut.UrunKategoriID = Convert.ToInt32(urun.UrunKategoriID.ToString());
            mevcut.UrunYoneticiID = Convert.ToInt32(Session["YoneticiName"].ToString());

            if (urunresim == null)
            {
                mevcut.UrunResmi = mevcut.UrunResmi;
            }
            else
            {
                Guid benzersiz = Guid.NewGuid();;
                dosyaYolu  = benzersiz.ToString();
                dosyaYolu += Path.GetFileName(urunresim.FileName);
                var yuklemeYeri = Path.Combine(Server.MapPath("~/resimler"), dosyaYolu);
                urunresim.SaveAs(yuklemeYeri);
                urun.UrunResmi   = dosyaYolu;
                mevcut.UrunResmi = urun.UrunResmi;
            }
            db.SaveChanges();
            return(RedirectToAction("Listele"));
        }
Example #5
0
 public static string SavePhoto(HttpPostedFileBase file)
 {
     var sourcePath = HttpContext.Current.Server.MapPath(ImgPath);
     var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
     file.SaveAs(Path.Combine(sourcePath, fileName));
     return ImgPath + fileName;
 }
Example #6
0
 /// <summary>
 /// 附件上传 成功:succeed、失败:error、文件太大:-1、
 /// </summary>
 /// <param name="file">单独文件的访问</param>
 /// <param name="path">存储路径</param>
 /// <param name="filename">输出文件名</param>
 /// <returns></returns>
 public static string FileUpload(HttpPostedFileBase file, string path, string FileName)
 {
     if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
     {
         Directory.CreateDirectory(path);
     }
     //取得文件的扩展名,并转换成小写
     string Extension = System.IO.Path.GetExtension(file.FileName).ToLower();
     //取得文件大小
     string filesize = SizeHelper.CountSize(file.ContentLength);
     try
     {
         int Size = file.ContentLength / 1024 / 1024;
         if (Size > 10)
         {
             return "-1";
         }
         else
         {
             file.SaveAs(path + FileName);
             return "succeed";
         }
     }
     catch (Exception ex)
     {
         return ex.Message;
     }
 }
        public ActionResult Create(Ruta art, HttpPostedFileBase file)
        {
            string fileName = "", path = "";
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder
                path = Path.Combine(Server.MapPath("~/Images/Uploads"), fileName);
                //string pathDef = path.Replace(@"\\", @"\");
                file.SaveAs(path);
            }

            try
            {
                fileName = "/Images/Uploads/" + fileName;
                ArticuloCEN cen = new ArticuloCEN();
                cen.New_(art.Descripcion, art.Precio, art.IdCategoria, fileName, art.Nombre);

                return RedirectToAction("PorCategoria", new { id=art.IdCategoria});
            }
            catch
            {
                return View();
            }
        }
Example #8
0
        public string updateImage(HttpPostedFileBase file, string objectName, string method)
        {
            if (file != null)
            {

                string filePath = "/Images/Members/" + objectName;

                string saveFileName = "/ProfilePicture" + ".png";// fileName;
                switch (method)
                {
                    case "HeadlineHeader":
                        filePath = "/Images/Headlines/" + objectName + "/";
                        var fileNameNoExtension = file.FileName;
                        fileNameNoExtension = fileNameNoExtension.Substring(0, fileNameNoExtension.IndexOf("."));
                        saveFileName = file.FileName.Replace(fileNameNoExtension, "header");

                        break;
                }
                string directoryPath = System.Web.HttpContext.Current.Server.MapPath(filePath);
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }

                string path = filePath + saveFileName;
                file.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~" + path));
                return path;
            }
            else return "";
        }
Example #9
0
        public FileDetail Add(HttpPostedFileBase upload, string saveDirectory)
        {
            if (upload == null || upload.ContentLength == 0)
            {
                throw new ArgumentNullException(nameof(upload));
            }

            var guid = Guid.NewGuid();
            var newFileName = guid + Path.GetExtension(upload.FileName);
            var file = new FileDetail
            {
                Id = guid,
                ContentType = upload.ContentType,
                OriginalFileName = Path.GetFileName(upload.FileName),
                FileName = newFileName,
                FilePath = Path.Combine(saveDirectory, newFileName)
            };

            upload.SaveAs(file.FilePath);

            this.UnitOfWork.FileDetails.Add(file);
            this.UnitOfWork.Commit();

            return file;
        }
Example #10
0
        public ActionResult FileUpload(HttpPostedFileBase file)
        {
            if (Request.Files.Count==0)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
            }

            string extension = Path.GetExtension(file.FileName);
            string filePathName = Guid.NewGuid().ToString("N") + extension;

            if (!Directory.Exists(@"c:\temp"))
            {
                Directory.CreateDirectory(@"c:\temp");
            }

            filePathName = @"c:\temp\" + filePathName;
            file.SaveAs(filePathName);

            Stream stream = file.InputStream;

            //using (FileStream fs = stream)
            //{

            //}

            ResumablePutFile("magiccook", Guid.NewGuid().ToString("N"),stream);

            return Json(new { success = true });
        }
 public ActionResult Edit(AdminGhiChuModel DM, HttpPostedFileBase Image)
 {
     try
     {
         if (Image != null)
         {
             ImageHelper imgHelper = new ImageHelper();
             string encodestring = imgHelper.encodeImageFile(Image);
             if (encodestring == "!")
                 return RedirectToAction("Index", "Error", new { errorMsg = "Can't upload Images" });
             var path = Path.Combine(Server.MapPath("~/Content/Images/GhiChu"), encodestring);
             Image.SaveAs(path);
             DM.HinhAnh = encodestring;
             DM.IdUser = null;
         }
         else
         {
             DM.IdUser = DM.IdUser > 0 ? DM.IdUser : null;
         }
         AdminGhiChuModel.Edit(DM);
         return RedirectToAction("Index", "AdminGhiChu");
     }
     catch
     {
         return RedirectToAction("Index", "Error");
     }
 }
        public ActionResult Create(HttpPostedFileBase page_img1, HttpPostedFileBase page_img2,HttpPostedFileBase page_img3 ,tbl_pagedetails _page)
        {
            tbl_pagedetails _tbl_page = new tbl_pagedetails();

                if (page_img1 != null)
                {
                    pic = Path.GetFileName(page_img1.FileName);
                    string path = System.IO.Path.Combine(Server.MapPath("~/images1/"), pic);
                    page_img1.SaveAs(path);
                }
                if (page_img2 != null)
                {
                    pic1 = Path.GetFileName(page_img2.FileName);
                    string path1 = System.IO.Path.Combine(Server.MapPath("~/images1/"), pic1);
                    page_img2.SaveAs(path1);
                }
                if (page_img3 != null)
                {
                    pic2 = Path.GetFileName(page_img3.FileName);
                    string path2 = System.IO.Path.Combine(Server.MapPath("~/images1/"), pic2);
                    page_img3.SaveAs(path2);
                }
                _tbl_page.page_content1 = Server.HtmlDecode(_page.page_content1);
                _tbl_page.page_content2 = Server.HtmlDecode(_page.page_content2);
                _tbl_page.page_content3 = Server.HtmlDecode(_page.page_content3);
                _tbl_page.page_img1 = pic;
                _tbl_page.page_img2 = pic1;
                _tbl_page.page_img3 = pic2;
                _tbl_page.page_header = _page.page_header;
                _tbl_page.menuid = _page.menuid;
                _tbl_page.BlogId = _page.BlogId;
                db.tbl_pagedetails.Add(_tbl_page);
                db.SaveChanges();
               return RedirectToAction("Index");
        }
        public ActionResult Create(PayMent payment, HttpPostedFileBase ImageUrl, string nameCus)
        {
            if (this.Session["Account"] == null)
            {
                return Redirect("/Login");
            }
            if(nameCus==null){
                TempData["a"] = "Xin chọn khách hàng";
                return View();
            }
            if (ModelState.IsValid)
            {
                PayMent newP = new PayMent();
                newP.UserId = Convert.ToInt32(this.Session["ID"]);
                newP.DatePay = DateTime.Now;
                newP.Cash = payment.Cash;
                newP.Invisible = false;
                newP.CustomerId = Convert.ToInt32(nameCus);

                if (ImageUrl != null)
                {

                    ImageUrl.SaveAs(HttpContext.Server.MapPath("~/img/") + ImageUrl.FileName);
                    newP.ImageUrl = ImageUrl.FileName;
                }
                db.PayMents.Add(newP);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View();
        }
Example #14
0
        public ActionResult Upload(HttpPostedFileBase upload)
        {
            if (upload == null)
            {
                ModelState.AddModelError("upload", "Please select a file");
            }
            else
            {
                string extension = Path.GetExtension(upload.FileName);
                if (!(extension ?? "").Equals(".nupkg", StringComparison.CurrentCultureIgnoreCase))
                {
                    ModelState.AddModelError("upload", "Invalid extension. Only .nupkg files will be accepted.");
                }
            }

            if (ModelState.IsValid)
            {
                var path = Path.Combine(Server.MapPath("~/Packages"), upload.FileName);
                upload.SaveAs(path);
                ViewBag.StatusMessage = new StatusMessage
                                            {
                                                Success = true,
                                                Message = String.Format("{0} was uploaded successfully.", upload.FileName)
                                            };
            }

            return View("Index");
        }
Example #15
0
        public string UploadFileToAzure(string FolderName, System.Web.HttpPostedFileBase file, string UserName, ref string LocalFolderPath, ref string LocalPath)
        {
            var    fileName  = Path.GetFileNameWithoutExtension(file.FileName);
            string refix     = "[" + fileName + "]_" + UserName + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string extension = Path.GetExtension(file.FileName);

            LocalFolderPath = "~/OtherFile/" + FolderName + "/";
            string FolderPath = System.Web.HttpContext.Current.Server.MapPath(LocalFolderPath);

            LocalPath = Path.Combine("~/OtherFile/" + FolderName, refix + extension);
            var destinationPath = Path.Combine(FolderPath, refix);

            if (!Directory.Exists(FolderPath))
            {
                Directory.CreateDirectory(FolderPath);
            }
            DirectoryInfo     dInfo     = new DirectoryInfo(FolderPath);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();

            dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
            dInfo.SetAccessControl(dSecurity);
            destinationPath += extension;
            file.SaveAs(destinationPath);
            return(new AzureHelper().UploadFile(FolderName, refix + extension, destinationPath));
        }
        public static bool ReplaceBylawsDocument(HttpPostedFileBase file)
        {
            string docsDir = GetBylawsDir();

            if (file.ContentLength > 0) {
                if (!Directory.Exists(docsDir))
                    Directory.CreateDirectory(docsDir);

                //SetBylawsDirPermissions();

                string old = GetBylawsDocument();
                if (!String.IsNullOrWhiteSpace(old))
                    File.Delete(Path.Combine(docsDir, old));

                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(docsDir, fileName);
                file.SaveAs(path);

                //SetBylawsDirPermissions();

                return true;
            }

            return false;
        }
        public ActionResult Create([Bind(Include = "ItemID,Name,CategoryID,Price,Blurb,Picture")] Item item,
            HttpPostedFileBase imageFile)
        {
            if (ModelState.IsValid)
            {
                Category category = db.Categories.Single(c => c.CategoryID == item.CategoryID);
                db.Items.Add(item);
                db.SaveChanges();

                if (imageFile != null)
                {
                    string imageName = System.IO.Path.GetFileName(imageFile.FileName);
                    var imagePath = new DisplayImage(DisplayImage.ImageCategory.Clothing);
                    // Property not constructed by ASP.NET
                    item.Category = db.Categories.Single(c => c.CategoryID == item.CategoryID);
                    string path = System.IO.Path.Combine(
                                        Server.MapPath("~/" + imagePath
                                            .GetPath(item, false)), imageName);
                    imageFile.SaveAs(path);
                }

                return RedirectToAction("Index");
            }

            ViewBag.CategoryID = SelectListHelper.GetCategoryList(item.Category, false);
            return View(item);
        }
Example #18
0
        /// <summary>
        /// Upload file
        /// </summary>
        /// <param name="pFiles">HttpPostedFileBase </param>
        /// <param name="pType">AppUpload.Logo</param>
        /// <returns>path file save database </returns>
        public static string PushFileToServer(System.Web.HttpPostedFileBase pFiles, string pType)
        {
            try
            {
                if (pFiles == null)
                {
                    return("");
                }
                //var name = pFiles.FileName;
                string _extension = System.IO.Path.GetExtension(pFiles.FileName);
                string path       = "/Content/Archive/" + pType + "/";

                string _filename = pFiles.FileName;
                _filename = convertToUnSign2(_filename);
                _filename = System.Text.RegularExpressions.Regex.Replace(_filename, "[^0-9A-Za-z.]+", "_");
                _filename = DateTime.Now.Ticks.ToString() + "_" + _filename;
                //_filename = Rename_file(pFiles.FileName);

                var f_part = HttpContext.Current.Server.MapPath(path) + _filename;
                pFiles.SaveAs(f_part);
                return(path + _filename);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return("");
            }
        }
        public ActionResult YeniUye(kullanicilar p1, System.Web.HttpPostedFileBase yuklenecekDosya)
        {
            if (yuklenecekDosya != null)
            {
                var supportedTypes = new[] { "jpg", "jpeg", "png" };

                var fileExt = System.IO.Path.GetExtension(yuklenecekDosya.FileName).Substring(1);

                if (!supportedTypes.Contains(fileExt))
                {
                    return(RedirectToAction("UyeGiris"));
                }

                string dosyaYolu   = Guid.NewGuid() + "." + fileExt;
                var    yuklemeYeri = Path.Combine(Server.MapPath("~/KlcDosyalar"), dosyaYolu);
                yuklenecekDosya.SaveAs(yuklemeYeri);

                p1.KResim = dosyaYolu;
            }
            else
            {
                if (p1.KCinsiyet == true)
                {
                    p1.KResim = "Erkek.png";
                }
                else
                {
                    p1.KResim = "Kadin.png";
                }
            }
            p1.YetkiID = 2;
            db.kullanicilar.Add(p1);
            db.SaveChanges();
            return(RedirectToAction("UyeGiris"));
        }
Example #20
0
        protected String SaveFile(HttpPostedFileBase file, String virtualPath)
        {
            //Check whether Image directory exists
            string physicalPath = Server.MapPath(virtualPath);
            if (!System.IO.Directory.Exists(physicalPath))
            {
                System.IO.Directory.CreateDirectory(physicalPath);
            }

            if (file != null && file.ContentLength > 0)
            {
                if (virtualPath == null)
                {
                    throw new ArgumentNullException("path cannot be null");
                }
                string pFileName = PrefixFName(file.FileName);
                String relpath = String.Format("{0}/{1}", virtualPath, pFileName);
                try
                {
                    file.SaveAs(Server.MapPath(relpath));
                    return pFileName;
                }
                catch (HttpException e)
                {
                    throw new ApplicationException("Cannot save uploaded file", e);
                }
            }
            return null;
        }
        public ActionResult Upload(HttpPostedFileBase file, string path)
        {
            try
            {
                var orig = path;
                if (file == null) throw new Exception("File not supplied.");
                if (!User.IsInRole("Files")) return Redirect(Url.Action<FilesController>(x => x.Browse(null)) + "?warning=Access Denied.");

                string root = ConfigurationManager.AppSettings["FilesRoot"];
                root = root.Trim().EndsWith(@"\") ? root = root.Substring(0, root.Length - 2) : root;

                if (!path.StartsWith("/")) path = "/" + path;

                path = string.Format(@"{0}{1}", ConfigurationManager.AppSettings["FilesRoot"], path.Replace("/", "\\"));

                var temp = path.EndsWith("\\") ? (path + file.FileName) : (path + "\\" + file.FileName);

                file.SaveAs(temp);
                return Redirect(Url.Action<FilesController>(x => x.Browse(orig)) + "?success=File Saved!");
            }
            catch (Exception ex)
            {
                return Redirect(Url.Action<FilesController>(x => x.Browse(null)) + "?error=" + Server.UrlEncode(ex.Message));
            }
        }
Example #22
0
        public ActionResult UploadRequire(string courseID)
        {
            DBHelper dbHelper = DBHelper.getMyHelper();
            //string attachFile = ConfigurationSettings.AppSettings["attachFile"].Trim();
            string showFileName = Request["UploadName"];

            System.Web.HttpPostedFileBase file = Request.Files["UploadFile"];
            //存入文件
            if (file.ContentLength > 0)
            {
                //先查看附件目录是否存在,不存在就创建,否则会报错 未找到路径。
                //  if (!System.IO.File.Exists(attachFile))
                //{
                //这个是根据路径新建一个目录
                //  System.IO.Directory.CreateDirectory(attachFile);
                //这个是根据路径新建一个文件,如果没有就会创建文件, 否则就会报错:对路径“...”的访问被拒绝。
                //System.IO.File.Create(attachFile);
                //}
                //这个是上传到当前项目的目录下,和Views文件夹同级
                file.SaveAs(Server.MapPath("~/") + System.IO.Path.GetFileName(file.FileName));
                //这个是上传到指定的目录下,必须指定具体的文件,不然会报错:对路径“...”的访问被拒绝。
                //file.SaveAs(attachFile + "\\" + System.IO.Path.GetFileName(showFileName));
            }
            //ViewBag.Result = System.IO.Path.GetFileName(file.FileName) + " 上传成功!";
            dbHelper.addRequire(courseID, Server.MapPath("~/") + System.IO.Path.GetFileName(file.FileName));
            return(RedirectToAction("EditCourseInfo", "Teacher", new { id = courseID }));
        }
        /// <summary>upload single file to file server</summary>
        /// <param name="fileVersionDTO">file version dto which contains information for file which is to be save</param>
        /// <param name="postedFile">Posted file which is to be save on file server</param>
        /// <returns>Success or failure of operation to save file on server wrapped in operation result</returns>
        public static OperationResult<bool> UploadSingleFileToServer(IFileVersionDTO fileVersionDTO, HttpPostedFileBase postedFile)
        {
            OperationResult<bool> result;
            try
            {
                if (fileVersionDTO != null && postedFile != null && postedFile.ContentLength > 0)
                {
                    if (Directory.Exists(fileVersionDTO.ServerPath))
                    {
                        var path = Path.Combine(
                            fileVersionDTO.ServerPath,
                            fileVersionDTO.ServerFileName);

                        postedFile.SaveAs(path);
                        result = OperationResult<bool>.CreateSuccessResult(true, "File Successfully Saved on file server.");
                    }
                    else
                    {
                        result = OperationResult<bool>.CreateFailureResult("Path doesn't exist.");
                    }
                }
                else
                {
                    result = OperationResult<bool>.CreateFailureResult("There is no file to save.");
                }
            }
            catch (Exception ex)
            {
                result = OperationResult<bool>.CreateErrorResult(ex.Message, ex.StackTrace);
            }

            return result;
        }
Example #24
0
        public ActionResult Create([Bind(Include = "Id,BillTypeNumber,BillTypeName,BillNumber,ContractNumber,FirstParty,SecondParty,SignDate,DueDate,Amount,ContractObject,ContractAttachmentType,ContractAttachmentName,ContractAttachmentUrl,Remark")] Contract contract, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {

                //{if (file != null)
                //    contract.ContractAttachmentType = file.ContentType;//获取图片类型
                //   contract.ContractAttachment = new byte[file.ContentLength];//新建一个长度等于图片大小的二进制地址
                //   file.InputStream.Read(contract.ContractAttachment, 0, file.ContentLength);//将image读取到Logo中
                //}

                if (!HasFiles.HasFile(file))
                {
                    ModelState.AddModelError("", "文件不能为空!");
                    return View(contract);
                }

                string miniType = file.ContentType;
                Stream fileStream =file.InputStream;
                string path = AppDomain.CurrentDomain.BaseDirectory + "files\\";
                string filename = Path.GetFileName(file.FileName);
                 file.SaveAs(Path.Combine(path, filename));

                   contract.ContractAttachmentType = miniType;
                    contract.ContractAttachmentName = filename;
                    contract.ContractAttachmentUrl = Path.Combine(path, filename);

                db.Contracts.Add(contract);//存储到数据库
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(contract);
        }
Example #25
0
        public ActionResult Create([Bind(Include="ID,TITLE,WRITER,WEBSITE,PUBLISHED_DATE,CONTENT,IMAGE_NAME,VIDEO_NAME")] PostItem postitem,
                                   HttpPostedFileBase imageFile, HttpPostedFileBase videoFile)
        {
            if (ModelState.IsValid)
            {
                if (imageFile != null)
                {
                    postitem.IMAGE_NAME = imageFile.FileName;
                }
                if (videoFile != null)
                {
                    postitem.VIDEO_NAME = videoFile.FileName;
                }
                db.Posts.Add(postitem);
                db.SaveChanges();

                // Checks whether the image / video file is not empty
                if (imageFile != null && imageFile.ContentLength > 0)
                {
                    string imageName = postitem.IMAGE_NAME;
                    string path = Server.MapPath("~/Uploads");
                    imageFile.SaveAs(Path.Combine(path, imageName));
                }
                if (videoFile != null && videoFile.ContentLength > 0)
                {
                    string videoName = postitem.VIDEO_NAME;
                    string path = Server.MapPath("~/Uploads");
                    videoFile.SaveAs(Path.Combine(path, videoName));
                }

                return RedirectToAction("Index");
            }

            return View(postitem);
        }
Example #26
0
        public ActionResult UploadProfileImage(HttpPostedFileBase file)
        {
            if (file != null)
            {
                string fileName = Guid.NewGuid().ToString() + ".jpg";
                string path = System.IO.Path.Combine(
                                       Server.MapPath("~/Images/Profile"), fileName);

                using (var db = new ApplicationDbContext())
                {
                    var userId = User.Identity.GetUserId();
                    var currentUser = db.Users.FirstOrDefault(u => u.Id == userId);
                    if (currentUser.ProfileImageUri != null)
                    {
                        var success = RemoveCurrentImage(currentUser.ProfileImageUri);
                    }
                    currentUser.ProfileImageUri = fileName;
                    db.Entry(currentUser).State = EntityState.Modified;
                    db.SaveChanges();
                }

                // file is uploaded
                file.SaveAs(path);

            }
            // after successfully uploading redirect the user
            return RedirectToAction("EditPublicProfile");
        }
        public ActionResult Create(EmployerFormViewModel employerForm, System.Web.HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
                var employer = Mapper.Map <EmployerFormViewModel, Employer>(employerForm);
                employer.CreatedBy  = "mdemirci"; //User.Identity.Name
                employer.CreateDate = DateTime.Now;
                employer.UpdatedBy  = "mdemirci";
                employer.UpdateDate = employer.CreateDate;
                if (upload != null)
                {
                    string dosyaYolu   = Path.GetFileName(upload.FileName);
                    var    yuklemeYeri = Path.Combine(Server.MapPath("~/Uploads/Employer"), dosyaYolu);
                    upload.SaveAs(yuklemeYeri);
                    employer.Logo = upload.FileName;
                }
                employerService.CreateEmployer(employer);
                employerService.SaveEmployer();
                return(RedirectToAction("Index"));
            }

            ViewBag.SectorId = new SelectList(sectorService.GetSectors(), "SectorId", "SectorName");
            ViewBag.CityId   = new SelectList(cityService.GetCities(), "CityId", "CityName");
            return(View(employerForm));
        }
Example #28
0
 public ActionResult Cbanner(string txt_banner, HttpPostedFileBase txt_file)
 {
     Banner b = new Banner();
     b.BMemo = txt_banner;
     //檢查是否有選擇檔案
     if (txt_file != null)
     {
         //檢查檔案大小要限制也可以在這裡做
         if (txt_file.ContentLength > 0)
         {
             string savedName = Path.Combine(Server.MapPath("~/images/Banner/"), txt_file.FileName);
             txt_file.SaveAs(savedName);
         }
     }
     if (txt_file == null)
     {
         b.BImg = "~/images/example_img.jpg";
     }
     else
     {
         b.BImg = "~/images/Banner/" + txt_file.FileName;
     }
     BannerData bd = new BannerData();
     bd.Create(b);
     return RedirectToAction("Conter", new { tabid = "2", m = "2" });
 }
        public static string Uploadfiles(string folder, HttpPostedFileBase file)
        {
            string UploadPath = "Upload";

            //提供平台特定的替换字符,该替换字符用于在反映分层文件系统组织的路径字符串中分隔目录级别
            var sep = Path.AltDirectorySeparatorChar.ToString();
            //指定为根目录
            var root = "~" + sep + UploadPath + sep;
            //拼接成路径
            var path = root + folder + sep;
            //找到这个路径
            var phicyPath = HostingEnvironment.MapPath(path);
            //判断是否存在,不存在创建一个
            if (!Directory.Exists(phicyPath))
            {
                Directory.CreateDirectory(phicyPath);
            }

            string extension = file.FileName.Substring(file.FileName.LastIndexOf('.'));

            string filename = CommonTools.ToUnixTime(System.DateTime.Now).ToString() + CommonTools.getRandomNumber() +
                              extension;

            file.SaveAs(phicyPath + filename);

            string fileuploadpath = "/" + UploadPath + "/" + folder + "/" + filename;

            return fileuploadpath;
        }
        public ActionResult Index(ImageModel imageModel, HttpPostedFileBase postedFile)
        {
            var relativePath = WebConfigurationManager.AppSettings["ImageCarouselRoute"];

            if (imageModel != null && ModelState.IsValid)
            {
                if (postedFile != null && postedFile.ContentLength > 0)
                {
                    Guid uniqueId = Guid.NewGuid();
                    var fileName = Path.GetFileName(postedFile.FileName);
                    var extension = Path.GetExtension(postedFile.FileName);
                    var contentType = postedFile.ContentType;

                    var internalName = uniqueId.ToString() + extension;
                    imageModel.Extension = extension;
                    imageModel.FileName = internalName;
                    imageModel.ContentType = contentType;

                    var physicalPath = Path.Combine(Server.MapPath("/"), relativePath, internalName);
                    postedFile.SaveAs(physicalPath);

                    var imageEntity = imageModel.ToEntity();
                    _service.Create(imageEntity);

                    return RedirectToAction("Index","Home");
                }
            }
            return View(imageModel);
        }
        public void upload(System.Web.HttpPostedFileBase aFile)
        {
            string file = aFile.FileName;
            string path = Server.MapPath("../Upload//");

            aFile.SaveAs(path + Guid.NewGuid() + "." + file.Split('.')[1]);
        }
Example #32
0
 public ActionResult Upload(HttpPostedFileBase file)
 {
     file.SaveAs(GetPath());
     InitScheduler();
     Index();
     return View("Index");
 }
        public ActionResult Index(string apiKey, string category, HttpPostedFileBase file)
        {
            if (_apiKey != apiKey) return Error("error api key");
            var filename = file.FileName;
            if (!_extensions.Any(c => filename.EndsWith(c)))
            {
                return Error("error extensions");
            }
            if (string.IsNullOrWhiteSpace(category) || _allowFolders.All(c => category != c))
            {
                return Error("error category");
            }
            var extenssion = Path.GetExtension(filename);
            if (string.IsNullOrWhiteSpace(extenssion) || _extensions.All(c => extenssion != c))
            {
                return Error("error extensions");
            }
            var path = new ResizingPath(category,extenssion);
        
            var physicalPath = Server.MapPath(path.PhysicalPath);
            if (!Directory.Exists(physicalPath))
            {
                Directory.CreateDirectory(physicalPath);
            }
            var physicalFilename= Server.MapPath(path.PhysicalFilename);
            file.SaveAs(physicalFilename);

            return Json(new {success = true,  format = path.VirtualFormatFilename});
        }
Example #34
0
        public ActionResult Create([Bind(Include = "Id,Title,MediaCaption,Body,MediaURL,Published")] Post post, HttpPostedFileBase fileUpload)
        {
            // Set Created date...
            if (ModelState.IsValid)
            {
                if (post.Body.Length < 20)
                {
                    ViewBag.Message = "Invalid Body - Must be at least 20 chars in length!";
                    return View(post);
                }

                // restrict the valid file formats to images only
                if (fileUpload != null && fileUpload.ContentLength > 0)
                {
                    if (!fileUpload.ContentType.Contains("image"))
                    {
                        return new HttpStatusCodeResult(HttpStatusCode.UnsupportedMediaType);
                    }
                    var fileName = Path.GetFileName(fileUpload.FileName);
                    var p = Path.Combine(Server.MapPath("~/img/blog/"), fileName);
                    fileUpload.SaveAs(p);
                    post.MediaURL = "~/img/blog/" + fileName;
                }
                post.Created = DateTime.UtcNow;
                db.Posts.Add(post);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(post);
        }
Example #35
0
        private FileProcessResult ProcessFile(HttpPostedFileBase file, int itemId, string origin, string originPathFormat)
        {
            var fileName = Path.GetFileName(file.FileName);
            var pFileName = string.Format("{0}_{1}", itemId, fileName);
            var path = Path.Combine(Server.MapPath(string.Format("~{0}", originPathFormat)), pFileName);
            file.SaveAs(path);

            // result
            var resultFile = new FileInfo(path);
            var resultUrlRightPart = string.Format("{0}{1}", originPathFormat, pFileName);
            var resultUrl = WebUtility.GetFullUrl(resultUrlRightPart);
            var result = new
            {
                relatedItemId = itemId,
                url = resultUrl,
                thumbnail_url = resultUrl,
                name = fileName,
                type = WebUtility.GetMIMEType(fileName),
                size = resultFile.Length,
                delete_url = WebUtility.GetFullUrl(string.Format("/files/delete?origin={0}&id={1}", origin, itemId)),
                delete_type = "POST"
            };

            return new FileProcessResult
            {
                ImagePath = path,
                ImageUrl = resultUrlRightPart,
                Result = result
            };
        }
        public ActionResult RegisterVolunteer(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                file.SaveAs(path);
            }

            //if (ModelState.IsValid)
            //{
            //    WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
            //        propertyValues: new
            //        {
            //            ContactFirstName = model.ContactFirstName,
            //            ContactLastName = model.ContactLastName,
            //            VolunteerHours = model.VolunteerHours,
            //            PhoneNumber = model.PhoneNumber,
            //            PhoneNoExtension = model.PhoneNoExtension,
            //            EmailAddress = model.EmailAddress
            //        });

            //}
            return View();
        }
Example #37
0
        public bool SaveFile(HttpPostedFileBase file, string entityName, string guid, int id)
        {
            var extension = Path.GetExtension(file.FileName);
            var dirInfo = string.Empty;

            try
            {
                if (extension != null)
                {
                    var vFileName = string.Format("{0};{1}", id > 0 ? Guid.NewGuid().ToString() : guid, Path.GetFileName(file.FileName));

                    if (HttpContext.Current.Request.PhysicalApplicationPath != null)
                        dirInfo = string.Format("{0}\\{1}\\{2}", Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, ConfigData.FileDirectory, entityName), id, vFileName);

                    if (HttpContext.Current.Request.PhysicalApplicationPath != null
                        && !Directory.Exists(string.Format("{0}\\{1}", Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, ConfigData.FileDirectory, entityName), id)))
                    {
                        Directory.CreateDirectory(string.Format("{0}\\{1}", Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, ConfigData.FileDirectory, entityName), id));
                    }
                }

                file.SaveAs(dirInfo);
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }
Example #38
0
        public ActionResult UploadFiles()
        {
            lock (objlock)
            {
                iCount++;

                string meth = Request.HttpMethod;
                string str  = string.Join(Environment.NewLine + Environment.NewLine + Environment.NewLine, Request.Params);

                foreach (string strKey in Request.Files)
                {
                    System.Web.HttpPostedFileBase pfb = Request.Files[strKey];

                    string SaveToPath = @"c:\temp";
                    SaveToPath = System.IO.Path.Combine(SaveToPath, pfb.FileName);

                    string mime = pfb.ContentType;
                    long   size = pfb.ContentLength;

                    pfb.SaveAs(SaveToPath);
                } // Next strKey

                Console.WriteLine(iCount);
                return(Content(Request.Params["index"]));
            } // End lock (objlock)
        }     // End Action UploadFiles
        /// <summary>
        /// Add a file
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string AddFile(string path)
        {
            string response;

            if (Request.Files.Count == 0 || Request.Files[0].ContentLength == 0)
            {
                response = Error("No file provided.");
            }
            else
            {
                if (!IsInRootPath(path))
                {
                    response = Error("Attempt to add file outside root path");
                }
                else
                {
                    System.Web.HttpPostedFileBase file = Request.Files[0];

                    if (!config.AllowedExtensions.Contains(Path.GetExtension(file.FileName).ToLower()))
                    {
                        response = Error("Uploaded file type is not allowed.");
                    }
                    else
                    {
                        //Only allow certain characters in file names
                        var baseFileName = Regex.Replace(Path.GetFileNameWithoutExtension(file.FileName), @"[^\w_-]", "");
                        var filePath     = Path.Combine(path, baseFileName + Path.GetExtension(file.FileName));
                        if (config.OverWrite == false)
                        {
                            //Make file name unique
                            var i = 0;
                            while (System.IO.File.Exists(Server.MapPath(filePath)))
                            {
                                i            = i + 1;
                                baseFileName = Regex.Replace(baseFileName, @"_[\d]+$", "");
                                filePath     = Path.Combine(path, baseFileName + "_" + i + Path.GetExtension(file.FileName));
                            }
                        }
                        else
                        {
                            if (System.IO.File.Exists(Server.MapPath(filePath)))
                            {
                                System.IO.File.Delete(Server.MapPath(filePath));
                            }
                        }
                        file.SaveAs(Server.MapPath(filePath));

                        response = json.Serialize(new
                        {
                            Path  = path,
                            Name  = Path.GetFileName(file.FileName),
                            Error = "No error",
                            Code  = 0
                        });
                    }
                }
            }
            return("<textarea>" + response + "</textarea>");
        }
Example #40
0
        public static string ImageSave(System.Web.HttpPostedFileBase file, string[] imageTypes, ref bool Value, string ImageName)
        {
            string ImagePath = string.Empty;

            if (file != null && file.ContentLength > 0)
            {
                if (!imageTypes.Contains(file.ContentType))
                {
                    Value = true;
                    return(ImagePath);
                }

                if (file.ContentLength > 2097152) // about 2 MB
                {
                    Value = true;
                    return(ImagePath);
                }
            }
            if (Value == false)
            {
                if (file != null && file.ContentLength > 0)
                {
                    string vehicleImageName = ImageName + "_" + String.Format("{0:yyyyMMdd}", DateTime.Now);
                    string extension        = System.IO.Path.GetExtension(file.FileName).ToLower();

                    String uploadFilePath = "\\Attachment\\";
                    // create a folder for distinct user -
                    string FolderName         = "VehicleImage";
                    string pathWithFolderName = HttpContext.Current.Server.MapPath(uploadFilePath + FolderName);

                    bool folderExists = Directory.Exists(pathWithFolderName);
                    if (!folderExists)
                    {
                        Directory.CreateDirectory(pathWithFolderName);
                    }

                    if (extension.ToLower() == ".pdf")
                    {
                        //string renamedFile = System.Guid.NewGuid().ToString("N");
                        string filePath = String.Format(pathWithFolderName + "\\{0}{1}", vehicleImageName, extension);
                        file.SaveAs(filePath);
                    }
                    else
                    {
                        using (var img = System.Drawing.Image.FromStream(file.InputStream))
                        {
                            string filePath = String.Format(pathWithFolderName + "\\{0}{1}", vehicleImageName, extension);

                            // Save large size image, 600 x 600
                            VaaaN.MLFF.Libraries.CommonLibrary.Common.CommonClass.SaveToFolder(img, extension, new System.Drawing.Size(600, 600), filePath);
                        }
                    }
                    ImagePath = vehicleImageName + extension;
                }
            }

            return(ImagePath);
        }
Example #41
0
        public void upload(System.Web.HttpPostedFileBase aFile)
        {
            string file     = aFile.FileName;
            string path     = Server.MapPath("../Upload//");
            string fileName = Guid.NewGuid() + "." + file.Split('.')[1];

            aFile.SaveAs(path + fileName);
            HttpContext.Response.Write(fileName);
        }
 public ActionResult DosyaYukle(System.Web.HttpPostedFileBase yuklenecekDosya)
 {
     if (yuklenecekDosya != null)
     {
         string dosyaYolu   = Path.GetFileName(yuklenecekDosya.FileName);
         var    yuklemeYeri = Path.Combine(Server.MapPath("~/Images"), dosyaYolu);
         yuklenecekDosya.SaveAs(yuklemeYeri);
     }
     return(View());
 }
Example #43
0
        public System.Web.Mvc.JsonResult StatusPost(vmMemberUserStatusPost objPost)
        {
            string exMessage_ = string.Empty;
            int    result     = 0;

            if (Request.IsAuthenticated)
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        System.Web.HttpPostedFileBase file = null;
                        string newfileName   = string.Empty;
                        string fileExtention = string.Empty;
                        string fileName      = string.Empty;

                        if (objPost != null)
                        {
                            if (Request.Files.Count > 0)
                            {
                                file          = Request.Files[0];
                                fileExtention = Path.GetExtension(file.FileName);
                                fileName      = Guid.NewGuid().ToString();
                                newfileName   = fileName + fileExtention;
                            }
                            System.Threading.Thread.Sleep(800);
                            object[] parameters = { objPost.PostBy, objPost.PostContent, newfileName, objPost.PostType, objPost.IsPrivate };

                            if (result == 1)
                            {
                                //Notify to all
                                //  NewsPostHub.BroadcastData();
                                if (Request.Files.Count > 0)
                                {
                                    string savelocation = Server.MapPath("../Areas/Social/Content/Files/Timeline/");
                                    if (Directory.Exists(savelocation) == false)
                                    {
                                        Directory.CreateDirectory(savelocation);
                                    }
                                    string savePath = savelocation + newfileName;
                                    file.SaveAs(savePath);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        exMessage_ = ex.ToString();
                        result     = -1;
                    }
                }
            }

            return(Json(new { Status = result, exMessage = exMessage_ }));
        }
Example #44
0
 public static string FileUpload(System.Web.HttpPostedFileBase file, string path)
 {
     if (file != null && file.ContentLength > 0)
     {
         file.SaveAs(HttpContext.Current.Server.MapPath(path + Utility.SetPagePlug(file.FileName.Split('.')[0].ToString()) + Path.GetExtension(file.FileName)));
         return(path + Utility.SetPagePlug(file.FileName.Split('.')[0].ToString()) + Path.GetExtension(file.FileName));
     }
     else
     {
         return("");
     }
 }
        /// <summary>
        /// Add a file
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string AddFile(string path)
        {
            string response;

            if (path.Where(c => c == '/').Count() <= 1)
            {
                response = Error("Sem permissão para gravar nesta pasta.");
            }
            else if (Request.Files.Count == 0 || Request.Files[0].ContentLength == 0)
            {
                response = Error("Nehum arquivo informado.");
            }
            else
            {
                if (!IsInRootPath(path))
                {
                    response = Error("Tentativa de adicionar arquivo fora da pasta raiz.");
                }
                else
                {
                    System.Web.HttpPostedFileBase file = Request.Files[0];
                    //if (!allowedExtensions.Contains(Path.GetExtension(file.FileName).ToLower()))
                    //{
                    //    response = Error("Tipo de arquivo não permitido.");
                    //}
                    //else
                    {
                        //Only allow certain characters in file names
                        var baseFileName = Regex.Replace(Path.GetFileNameWithoutExtension(file.FileName), @"[^\w_-]", "");
                        var filePath     = Path.Combine(path, baseFileName + Path.GetExtension(file.FileName));

                        //Make file name unique
                        var i = 0;
                        while (System.IO.File.Exists(ObtenhaCaminho(filePath)))
                        {
                            i            = i + 1;
                            baseFileName = Regex.Replace(baseFileName, @"_[\d]+$", "");
                            filePath     = Path.Combine(path, baseFileName + "_" + i + Path.GetExtension(file.FileName));
                        }
                        file.SaveAs(ObtenhaCaminho(filePath));

                        response = json.Serialize(new
                        {
                            Path  = path,
                            Name  = Path.GetFileName(file.FileName),
                            Error = "No error",
                            Code  = 0
                        });
                    }
                }
            }
            return("<textarea>" + response + "</textarea>");
        }
Example #46
0
        public ActionResult Upload(string taskreq, string courseid, string taskid, string taskmaxtimes)
        {
            /// <summary>
            /// 上传操作
            /// </summary>
            /// <returns></returns>
            //string attachFile = ConfigurationSettings.AppSettings["attachFile"].Trim();
            string showFileName = Request["UploadName"];

            System.Web.HttpPostedFileBase file = Request.Files["UploadFile"];
            //存入文件
            if (file.ContentLength > 0)
            {
                //先查看附件目录是否存在,不存在就创建,否则会报错 未找到路径。
                //if (!System.IO.File.Exists(attachFile))
                //{
                //这个是根据路径新建一个目录
                //   System.IO.Directory.CreateDirectory(attachFile);
                //这个是根据路径新建一个文件,如果没有就会创建文件, 否则就会报错:对路径“...”的访问被拒绝。
                //System.IO .File.Create(attachFile);
                //}
                //这个是上传到当前项目的目录下,和Views文件夹同级
                file.SaveAs(Server.MapPath("~/homework/") + System.IO.Path.GetFileName(file.FileName));
                //这个是上传到指定的目录下,必须指定具体的文件,不然会报错:对路径“...”的访问被拒绝。
                //file.SaveAs(attachFile + "\\" + System.IO.Path.GetFileName(showFileName));
            }
            //ViewBag.Result = System.IO.Path.GetFileName(file.FileName) + " 上传成功!";
            //List<TaskSubmit> tslist = dbHelper.getTaskSubmits();
            List <UserCourse> uclist        = dbHelper.getUserCourses();
            HttpCookie        accountCookie = Request.Cookies["Account"];
            string            userId        = accountCookie["userName"];
            string            groupid       = "0";

            foreach (UserCourse usercourse in uclist)
            {
                if (usercourse.userId == userId && usercourse.courseId == courseid)
                {
                    groupid = usercourse.groupId;
                }
            }
            DateTime submittime  = System.DateTime.Now;
            string   submittimes = "0";
            int      taskgrade   = 0;
            string   taskcomment = "";
            string   submitterid = userId;
            string   taskurl     = Server.MapPath("~/homework/") + System.IO.Path.GetFileName(file.FileName);

            dbHelper.addTaskSubmit(groupid, taskid, submittime, userId, submittimes, taskgrade, taskcomment, submitterid, courseid, taskurl);

            return(RedirectToAction("TaskInfo", "Student", new { TaskReq = taskreq, courseId = courseid, TaskId = taskid, TaskMaxTimes = taskmaxtimes }));
        }
Example #47
0
        public ActionResult UyeCreate(string KullaniciAdi, string Sifre, int Yetki, string Ad, string Soyad, string Email, int Aktif, System.Web.HttpPostedFileBase Image, string Yas, string Telefon, string Adres)
        {
            Session["SayfaAdi"] = "UyeEkle";

            string GuidKey     = Guid.NewGuid().ToString();
            string dosyaYolu   = GuidKey + ".png";
            var    yuklemeYeri = Path.Combine(Server.MapPath("~/Dosyalar/"), dosyaYolu);

            Image.SaveAs(yuklemeYeri);
            var SaveImage = "/Dosyalar/" + dosyaYolu;

            AdminWebServis.WebService Veri = new AdminWebServis.WebService();
            Veri.UyeCreate(KullaniciAdi, Sifre, Yetki, Ad, Soyad, Email, Aktif, SaveImage, Yas, Adres, Telefon);
            return(RedirectToAction("../Admin/UyeList"));
        }
Example #48
0
        public ActionResult MakaleCreate(string KisaIcerikTr, string KisaIcerikEn, string IcerikTr, string IcerikEn, System.Web.HttpPostedFileBase Image, int Aktif, int MakaleYayinSira, string RouteTr)
        {
            string GuidKey     = Guid.NewGuid().ToString();
            string dosyaYolu   = GuidKey + ".png";
            var    yuklemeYeri = Path.Combine(Server.MapPath("~/Dosyalar/"), dosyaYolu);

            Image.SaveAs(yuklemeYeri);
            var SaveImage = "/Dosyalar/" + dosyaYolu;

            Session["SayfaAdi"] = "MakaleCreate";

            AdminWebServis.WebService Veri = new AdminWebServis.WebService();
            Veri.MakaleCreate(KisaIcerikTr, KisaIcerikEn, IcerikTr, IcerikEn, SaveImage, Aktif, MakaleYayinSira, RouteTr);
            return(RedirectToAction("../Admin/MakaleList"));
        }
Example #49
0
 public ActionResult Dokumanteler(System.Web.HttpPostedFileBase PATH, Documents _docs)
 {
     using (db)
     {
         if (!String.IsNullOrEmpty(_docs.PATH))
         {
             string dosyaYolu   = Path.GetFileName(PATH.FileName);
             var    yuklemeYeri = Path.Combine(Server.MapPath("~/Dokumantasyonlar"), dosyaYolu);
             PATH.SaveAs(yuklemeYeri);
             int affectedRows = db.Execute("insert into Documents (PATH,ACIKLAMA) values " +
                                           "('" + PATH.FileName + "','" + _docs.ACIKLAMA + "')");
         }
     }
     return(RedirectToAction("Dokumanteler"));
 }
        public ActionResult Olustur(string evrakAd, System.Web.HttpPostedFileBase yuklenecekDosya)
        {
            if (yuklenecekDosya != null)
            {
                try
                {
                    string dosyaAd      = Path.GetFileName(yuklenecekDosya.FileName);
                    var    yuklenmeYeri = Path.Combine(Server.MapPath("~/Evraklar"), dosyaAd);
                    string evrakYol     = "/Evraklar/" + dosyaAd;

                    yuklenecekDosya.SaveAs(yuklenmeYeri);

                    int personelId = Convert.ToInt32(Session["personelId"]);

                    Evraklar evrak = new Evraklar();
                    evrak.evrakAd      = evrakAd;
                    evrak.perId        = personelId;
                    evrak.evrakYol     = evrakYol;
                    evrak.evrakTarih   = DateTime.Now;
                    evrak.evrakDurumId = 1;
                    evrak.evrakYerId   = 1;

                    entity.Evraklar.Add(evrak);
                    entity.SaveChanges();

                    Raporlar rapor = new Raporlar();
                    rapor.evrakId    = evrak.evrakId;
                    rapor.personelId = personelId;
                    rapor.tarih      = DateTime.Now;
                    rapor.durumId    = 1;
                    rapor.yerId      = 1;

                    entity.Raporlar.Add(rapor);
                    entity.SaveChanges();

                    return(RedirectToAction("Takip", "Kullanici"));
                }
                catch (Exception)
                {
                    return(RedirectToAction("Index", "Kullanici"));
                }
            }
            else
            {
                return(View());
            }
        }
Example #51
0
        public SOPORTES CREAR(decimal _COD_RETIRO, decimal _COD_TIPO_SOPORTE, string _NOMBRE_SOPORTE,
                              string _USUARIO, System.Web.HttpPostedFileBase _ARCHIVO)

        {
            try
            {
                string INFO = ("Iniciando Método CREAR por _COD_RETIRO : " + _COD_RETIRO);
                log.Info("CODIGO : LGSO3," + INFO);

                Thread HILO = new Thread(() => TRAZA.DEPURAR_TRAZA("LGRE3", log.Logger.Name, "CREAR", INFO));
                HILO.Start();


                var      _NOMBRE_SOPORTE_COD = _COD_RETIRO.ToString() + "_" + HashSHA(Path.GetFileName(_NOMBRE_SOPORTE));
                SOPORTES SOPORTE             = new SOPORTES();
                string   _RUTA_SOPORTE       = System.Configuration.ConfigurationManager.AppSettings["Ruta_Descarga_archivos"].ToString();

                string RUTA_ARCHIVO = _RUTA_SOPORTE + _NOMBRE_SOPORTE_COD + Path.GetExtension(_NOMBRE_SOPORTE);

                SOPORTE.COD_RETIRO           = _COD_RETIRO;
                SOPORTE.COD_TIPO_SOPORTE     = _COD_TIPO_SOPORTE;
                SOPORTE.RUTA_SOPORTE         = RUTA_ARCHIVO;
                SOPORTE.NOMBRE_SOPORTE       = _NOMBRE_SOPORTE;
                SOPORTE.APROBADO             = false;
                SOPORTE.ESTADO               = 0;
                SOPORTE.COD_USUARIO_CREA     = _USUARIO;
                SOPORTE.FECHA_CREA           = DateTime.Now;
                SOPORTE.COD_USUARIO_MODIFICA = _USUARIO;
                SOPORTE.FECHA_MODIFICA       = DateTime.Now;
                SOPORTE.TAMANO               = (_ARCHIVO.ContentLength / 1024).ToString() + "k";
                _REPOSITORIO.CREAR_SOPORTE(SOPORTE);
                _REPOSITORIO.GUARDAR();
                _ARCHIVO.SaveAs(RUTA_ARCHIVO);
                return(SOPORTE);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("CODIGO : LGSO3,  Método CREAR por _COD_RETIRO : {0}, {1} ", _COD_RETIRO, ex.StackTrace);
                ex.HelpLink = (ex.HelpLink == "" || ex.HelpLink == null ? "LGSO3" : ex.HelpLink);
                Thread HILO = new Thread(() => ERROR.ERROR_TRAZA(ex.HelpLink, log.Logger.Name, ex.TargetSite.Name, ex.StackTrace));
                HILO.Start();

                throw ex;
            }
        }
Example #52
0
        /// <summary>
        /// Deletes the old image (if any) and replaces with new, else just saves the new image
        /// </summary>
        /// <param name="oldImageName">sql to fetch a string of the existing image path</param>
        /// <param name="imgType">Used in prefixing img name. E.g. GeoTree, Acc, Pkg...</param>
        /// <param name="itemId">Parent records primary key</param>
        /// <param name="UploadedFile">HttpPostedFileBase</param>
        /// <returns></returns>
        protected string SaveImage(PetaPoco.Sql oldImageName, string imgType, int itemId, System.Web.HttpPostedFileBase UploadedFile)
        {
            string fn     = "";
            string oldImg = "";

            if (UploadedFile != null)
            {
                //First remove the old img (if exists)
                //if (oldImg?.Length > 0) System.IO.File.Delete(System.IO.Path.Combine(Server.MapPath("~/Images"), oldImg));

                //Save the new file
                fn = UploadedFile.FileName.Substring(UploadedFile.FileName.LastIndexOf('\\') + 1);
                fn = String.Concat(imgType, "_", itemId.ToString(), "_", fn);
                string SavePath = System.IO.Path.Combine(Server.MapPath("~/Images"), fn);
                UploadedFile.SaveAs(SavePath);
            }
            return((fn.Length > 0) ? fn : oldImg);
        }
Example #53
0
        public ActionResult Add(FormCollection form, System.Web.HttpPostedFileBase urunresim)
        {
            string  dosyaYolu = "";
            Urunler model     = new Urunler();

            model.UrunName  = form["UrunName"];
            model.UrunFiyat = Convert.ToInt32(form["UrunFiyat"]);
            //  model.UrunResmi = form["urunresim"];
            model.UrunAciklama = form["UrunAciklama"];

            if (Session["YoneticiName"] == null)
            {
                model.UrunYoneticiID = -1;
            }
            else
            {
                model.UrunYoneticiID = Convert.ToInt32(Session["YoneticiName"].ToString());
            }


            model.UrunKategoriID = Convert.ToInt32(form["UrunKategoriID"]);

            if (urunresim != null)
            {
                Guid benzersiz = Guid.NewGuid();;
                dosyaYolu  = benzersiz.ToString();
                dosyaYolu += Path.GetFileName(urunresim.FileName);
                var yuklemeYeri = Path.Combine(Server.MapPath("~/resimler"), dosyaYolu);
                urunresim.SaveAs(yuklemeYeri);
                model.UrunResmi = dosyaYolu;
            }
            else
            {
                model.UrunResmi = "ResimYok.png";
            }



            db.Urunler.Add(model);
            db.SaveChanges();

            return(RedirectToAction("Listele"));
        }
Example #54
0
        public async Task <ActionResult> Create([Bind(Include = "Id,State,Name,ImageUrl")] Campaign campaign
                                                , System.Web.HttpPostedFileBase image)
        {
            // temp
            if (null != image)
            {
                image.SaveAs(UPLOADS + image.FileName);
            }

            if (ModelState.IsValid)
            {
                campaign.Id = Guid.NewGuid();
                db.Campaigns.Add(campaign);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(campaign));
        }
Example #55
0
 /// <summary>
 /// Upload file
 /// </summary>
 /// <param name="pFiles">HttpPostedFileBase </param>
 /// <param name="pType">AppUpload.Logo</param>
 /// <returns>path file save database </returns>
 public static string PushFileToServer(System.Web.HttpPostedFileBase pFiles, string pType)
 {
     try
     {
         if (pFiles == null)
         {
             return("");
         }
         var name = pFiles.FileName;
         name = System.IO.Path.GetExtension(pFiles.FileName);
         string path   = "/Content/Archive/" + pType + "/";
         var    f_part = HttpContext.Current.Server.MapPath(path) + pFiles.FileName;
         pFiles.SaveAs(f_part);
         return(path + pFiles.FileName);
     }
     catch (Exception ex)
     {
         Logger.LogException(ex);
         return("");
     }
 }
Example #56
0
        public JsonResult FileUploadAjax(System.Web.HttpPostedFileBase Dosya)
        {
            if (Dosya != null)
            {
                AdminWebServis.WebService Veri = new AdminWebServis.WebService();
                if (!Path.GetExtension(Dosya.FileName).Equals(".png"))
                {
                    return(base.Json("Yanlış dosya tipi!Lütfen Png Formatında Yükleme Yapınız!"));
                }
                string GuidKey = Guid.NewGuid().ToString();

                string dosyaYolu   = GuidKey + ".png";
                var    yuklemeYeri = Path.Combine(Server.MapPath("~/Dosyalar"), dosyaYolu);
                Dosya.SaveAs(yuklemeYeri);
                var SavePath = "/Dosyalar/" + dosyaYolu;

                Veri.DosyaCreate(SavePath);
                return(Json("Resim Sisteme Yüklenmiştir...", JsonRequestBehavior.AllowGet));
            }
            return(Json("Yükleme Sırasında Hata Oluştu!!!", JsonRequestBehavior.AllowGet));
        }
Example #57
0
        public ActionResult Create(DocumentViewModel DVM, System.Web.HttpPostedFileBase file)
        {
            Document D = new Document();

            D.DocumentId   = DVM.DocumentId;
            D.DocumentName = DVM.DocumentName;
            D.Size         = DVM.Size;

            D.categorie = (Domain.Entities.Categorie)DVM.categorie;
            try
            {
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path     = Path.Combine(Server.MapPath("~/Content/Documents/"), fileName);

                    file.SaveAs(path);
                    D.Path          = "~/Content/Documents/" + fileName;
                    ViewBag.Message = "File Uploaded Successfully!!";
                }
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return(View());
            }
            D.DateCreation = DateTime.Now;

            DS.Add(D);
            DS.Commit();
            if (DVM.categorie == Web.Models.Categorie.Image)
            {
                return(View("Index"));
            }

            else
            {
                return(View("IndexDocument"));
            }
        }
Example #58
0
 public ActionResult Edit(ApplicationUser model, System.Web.HttpPostedFileBase file)
 {
     if (ModelState.IsValid)
     {
         ApplicationUser u = UserManager.FindByEmail(model.UserName);
         u.UserName    = model.Email;
         u.Email       = model.Email;
         u.FirstName   = model.FirstName; // Extra Property
         u.LastName    = model.LastName;  // Extra Property
         u.ImagePath   = model.ImagePath;
         u.PhoneNumber = model.PhoneNumber;
         if (file != null && file.ContentLength > 0)
         {
             string dosyaYolu   = Path.GetFileName(file.FileName);
             var    yuklemeYeri = Path.Combine(Server.MapPath("~/Uploads/Account"), dosyaYolu);
             file.SaveAs(yuklemeYeri);
             u.ImagePath = file.FileName;
         }
         UserManager.Update(u);
         return(RedirectToAction("Index"));
     }
     return(View(model));
 }
Example #59
0
        public void UpdateUserLogo(string userId, System.Web.HttpPostedFileBase userLogoFile)
        {
            string fileName = System.IO.Path.GetFileName(userLogoFile.FileName);
            //save file

            string fullPathName = GetServerPath("~/Content/MidTerm/") + fileName;

            userLogoFile.SaveAs(fullPathName);

            string newName = GetServerPath("~/Content/User-logo/") + userId + ".jpg";

            if (System.IO.File.Exists(newName))
            {
                System.IO.File.Delete(newName);
            }
            System.Drawing.Image imNormal = System.Drawing.Image.FromFile(fullPathName);
            imNormal = new ImageHandler().ResizeImage(imNormal, 300);
            imNormal.Save(newName);
            imNormal = new ImageHandler().ResizeImage(imNormal, 80);
            imNormal.Save(GetServerPath("~/Content/User-logo/") + userId + "_small.jpg");

            System.IO.File.Delete(fullPathName);
        }
        public ActionResult Index(Products products, System.Web.HttpPostedFileBase photo)
        {
            var user = Session["user"];

            if (user == null)
            {
                return(RedirectToAction("Index", "Login"));
            }
            else
            {
                string resimAd       = Path.GetFileName(photo.FileName);
                var    yuklenecekyer = Path.Combine(Server.MapPath("~/Resimler"), resimAd);
                string resimyol      = "~/Resimler/" + resimAd;
                photo.SaveAs(yuklenecekyer);

                products.ProductPicture = resimyol;

                _productServices.Add(products);


                return(RedirectToAction("Index", "Home"));
            }
        }