public ActionResult UploadLogo(AddLogo logo, HttpPostedFileBase file) { RDN.Library.Classes.Team.TeamFactory.SaveLogoToDbForTeam(file, new Guid(), logo.TeamName); ViewBag.Saved = true; ApiCache.ClearCache(); return View(logo); }
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; }
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)); }
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 bool ValidatePhotoUploaded(System.Web.HttpPostedFileBase uploadedFile) { if (uploadedFile == null) { return(false); } if (uploadedFile.ContentLength <= 0) { return(false); } var imageContentTypes = new string[] { "image/png", "image/JPEG" }; var imageFileExtentions = new string[] { ".png", ".jpg", ".jpeg" }; var isImage = imageContentTypes.Any(x => x.Equals(uploadedFile.ContentType, StringComparison.CurrentCultureIgnoreCase)); var isValidExtention = imageFileExtentions.Any(x => x.Equals(System.IO.Path.GetExtension(uploadedFile.FileName) ?? "", StringComparison.CurrentCultureIgnoreCase)); if (!isImage || !isValidExtention) //if not a valid extention or content type is not image... { return(false); } if (uploadedFile.ContentLength > 2096 * 1024)//greater than 4MB { return(false); } return(true); }
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")); }
/// <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 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 ""; }
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 })); }
public ActionResult Create(Product product, HttpPostedFileBase image) { if (ModelState.IsValid) { if (image != null) { product.ImageMimeType = image.ContentType; product.ImageData = new byte[image.ContentLength]; image.InputStream.Read(product.ImageData, 0, image.ContentLength); } else { byte[] imageByte = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/defaultProduct.gif")); product.ImageData = imageByte; product.ImageMimeType = "image/gif"; } // Date product was created product.UserId = WebSecurity.GetUserId(User.Identity.Name); product.DataCreated = DateTime.Now; db.Products.Add(product); db.SaveChanges(); return RedirectToAction("Index"); } return View(product); }
public static bool IsImageFile(HttpPostedFileBase photoFile) { using (var img = Image.FromStream(photoFile.InputStream)) { return img.Width > 0; } }
public static bool IsWebFriendlyImage(HttpPostedFileBase file) { //check for actual object if (file == null) { return false; } //check size - file must be less than 2MB and greater than 1KB if (file.ContentLength > 2 * 1024 * 1024 || file.ContentLength < 1024) { return false; } try { using (var img = Image.FromStream(file.InputStream)) { return ImageFormat.Jpeg.Equals(img.RawFormat) || ImageFormat.Png.Equals(img.RawFormat) || ImageFormat.Gif.Equals(img.RawFormat); } } catch { return false; } }
public ActionResult Create(CreateCustomerViewModel model, HttpPostedFileBase file) { if (ModelState.IsValid) { RegisterModel registerModel = model.RegisterModel; // Attempt to register the user MembershipCreateStatus createStatus; MembershipUser msu = Membership.CreateUser(registerModel.UserName, registerModel.Password, registerModel.Email, null, null, true, null, out createStatus); if (createStatus == MembershipCreateStatus.Success) { model.Customer.Image = new byte[file.ContentLength]; file.InputStream.Read(model.Customer.Image, 0, file.ContentLength); model.Customer.UserName = msu.UserName; model.AccessControl.UserName = msu.UserName; db.AccessControls.Add(model.AccessControl); db.Customers.Add(model.Customer); db.SaveChanges(); Roles.AddUserToRole(msu.UserName, "Customer"); // create a customer user return View("Complete", model.Customer); //For Develope use this model } else { ModelState.AddModelError("", ErrorCodeToString(createStatus)); } } // If we got this far, something failed, redisplay form return View(model); }
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; }
public ActionResult UploadTemp(System.Web.HttpPostedFileBase file) { var target = FileId.FromFileName(file.FileName); _FileManager.CreateTemp(target, file.InputStream); return(SuccessJsonResult <object>(new { id = target.ToTempId() })); }
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 }); }
/// <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(); } }
public ActionResult Index(HttpPostedFileBase uploadFile) { if (uploadFile.ContentLength > 0) { var streamReader = new StreamReader(uploadFile.InputStream); var gtinList = new List<string>(); while (!streamReader.EndOfStream) { gtinList.Add(streamReader.ReadLine()); } var productsWithInfo = new List<string>(); var productsWithAdvices = new List<string>(); foreach (var gtin in gtinList) { var result = _productApplicationService.FindProductByGtin(gtin, true); if (!string.IsNullOrEmpty(result.ProductName)) { productsWithInfo.Add(result.ProductName); } if (result.ProductAdvices.Count > 0 || result.Brand.BrandAdvices.Count > 0 || (result.Brand.Owner != null && result.Brand.Owner.CompanyAdvices.Count > 0) || result.Ingredients.Any(x => x.IngredientAdvices.Count > 0)) { productsWithAdvices.Add(result.ProductName); } } ViewData["ProdWithInfo"] = productsWithInfo; ViewData["ProdWithAdvices"] = productsWithAdvices; } return View(); }
public override System.Web.Mvc.ActionResult UploadPackage(System.Web.HttpPostedFileBase uploadFile) { var callInfo = new T4MVC_ActionResult(Area, Name, ActionNames.UploadPackage); callInfo.RouteValueDictionary.Add("uploadFile", uploadFile); return(callInfo); }
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
public ActionResult Create(CreateCourseScoViewModel form, HttpPostedFileBase file) { var filePackage = FileServices.Upload_Backup_and_then_ExtractZip(file, Server, AppConstants.ScoDirectory); if (!ModelState.IsValid || filePackage == null) return View(form); var sco = new Sco { Title = filePackage.Name, Directory = filePackage.Directory }; _context.Scos.Add(sco); _context.SaveChanges(); //Add the sco to the new CourseSco and save var courseSco = new CourseSco { Title = sco.Title, CourseTemplateId = form.CourseId, CatalogueNumber = form.CatalogueNumber, RequiredScoId = form.RequiredScoId, ScoId = sco.Id }; _context.CourseScos.Add(courseSco); _context.SaveChanges(); return RedirectToAction("Index", new { id = form.CourseId }); }
public async Task<string> UploadFile(string fileName, HttpPostedFileBase file) { // TODO: // https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/#programmatically-access-blob-storage // - Add proper nuget // - Connect to storage // - create container // - upload blob // - return URL // Retrieve storage account from connection string. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]); // Create the blob client. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve a reference to a container. CloudBlobContainer container = blobClient.GetContainerReference(ContainerName); // Create the container if it doesn't already exist. container.CreateIfNotExists(); // Retrieve reference to a blob named "myblob". CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName); await blockBlob.UploadFromStreamAsync(file.InputStream); return blockBlob.Uri.ToString(); }
public ActionResult Create(Personnel personnel, HttpPostedFileBase file) { if (ModelState.IsValid) { try { //image upload if (file == null || !isImageValid(file)) { ModelState.AddModelError(string.Empty, string.Empty); } else { isActivePersonel(personnel); db.Insert(personnel); //Save Image File to Local string imagePath = "~/Uploads/Images/" + "Image_" + personnel.ID + ".png"; saveImage(file, imagePath); //Save Image Path to DB and Update Personnel personnel.PhotoPath = imagePath; db.Update(personnel); return RedirectToAction("Index"); } } catch (Exception) { throw; } } return View(personnel); }
public static UploadResult UploadImage(HttpPostedFileBase fileimage) { try { if (fileimage == null) { return new UploadResult { IsSuccess = false, FileName = "", Result = "", ImageThumbnail = "" }; } if (!ExtentionFile.CheckExtentionFileImage(fileimage.FileName.ToLower())) { return new UploadResult { IsSuccess = false, FileName = "", Result = ConstantStrings.ExtensionImageSupport, ImageThumbnail = "" }; } if (fileimage.ContentLength > Maxlengthfile) { return new UploadResult { IsSuccess = false, FileName = "", Result = ConstantStrings.MaxLengthFileSupport, ImageThumbnail = "" }; } CreateFolder(Rootimage); var filename = string.Format("{0}.{1}", GetStringTimes.GetTimes(DateTime.Now), ExtentionFile.GetExtentionFileImageString(fileimage.FileName.ToLower())); fileimage.SaveAs(GetTempUploadImagePath(filename)); GenerateThumbNail(filename, Heightthumbnail); return new UploadResult { IsSuccess = true, FileName = filename, Result = ConstantStrings.UploadSuccess, ImageThumbnail = filename }; } catch (Exception) { return new UploadResult { IsSuccess = false, FileName = "", Result = ConstantStrings.UploadNonSuccess, ImageThumbnail = "" }; } }
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"); }
public ActionResult AddFileToTitle(string wikiname, int tid,HttpPostedFileBase file, ViewTitleFile mod) { try { if (CommonTools.isEmpty(wikiname) && tid <= 0) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } mod.File = new WikiFile(); WikiTitle title = CommonTools.titlemngr.GetTitlebyId(wikiname, tid); mod.Title = title; if ( mod !=null && mod.File !=null && mod.Title !=null && file.ContentLength>0) { WikiFile fmod = mod.File; this.filemngr.AddFile(wikiname, mod.File, file, tid, CommonTools.usrmng.GetUser(this.User.Identity.Name)); } return View(mod); } catch (Exception ex) { CommonTools.ErrorReporting(ex); return new HttpStatusCodeResult(System.Net.HttpStatusCode.InternalServerError); } }
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); }
public void Read(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { var reader = new BinaryReader(file.InputStream); byte[] binData = reader.ReadBytes((int)file.InputStream.Length); string result = System.Text.Encoding.UTF7.GetString(binData); var strings = result.Split('\r','\n').Where(x => !string.IsNullOrWhiteSpace(x)); foreach (var s in strings) { var show = s.Trim(); var indexOfFirstSpace = show.IndexOf(' '); var dateStr = show.Substring(0, indexOfFirstSpace); if (dateStr.Length == 6) { dateStr = "20" + dateStr; } var date = DateTime.ParseExact(dateStr, "yyyyMMdd", CultureInfo.InvariantCulture); var showStr = show.Substring(indexOfFirstSpace, show.Length - indexOfFirstSpace).Trim(); string artist; if (!showStr.Contains('-')) { artist = showStr; CreateShow(date, artist); } else { var placeAndArtist = showStr.Split('-'); artist = placeAndArtist[1].Trim(); Venue venue; if (placeAndArtist[0].Contains(',')) { var venueAndCity = placeAndArtist[0].Split(','); venue = new Venue { Name = venueAndCity[0], City = venueAndCity[1] }; } else { venue = new Venue { Name = placeAndArtist[0].Trim() }; } CreateShow(date, artist, venue); } } } }
/// <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; }
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")); }
public ThemeUploader(string tenant, HttpPostedFileBase postedFile) { this.Tenant = tenant; this.PostedFile = postedFile; this.ThemeInfo = new ThemeInfo(); this.SetUploadPaths(); }
public static FTPResultFile UploadFile(FtpModel model, HttpPostedFileBase file) { FTPResultFile result = null; try { string ftpfullpath = model.Server + model.Directory + file.FileName; FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); ftp.Credentials = new NetworkCredential(model.Username, model.Password); ftp.KeepAlive = true; ftp.UseBinary = true; ftp.Method = WebRequestMethods.Ftp.UploadFile; Stream fs = file.InputStream; byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); Stream ftpstream = ftp.GetRequestStream(); ftpstream.Write(buffer, 0, buffer.Length); ftpstream.Close(); result.IsSuccess = true; } catch (Exception ex) { result.Exception = ex; result.IsSuccess = false; } return result; }
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)); } }
public ActionResult Create(PhotoGalleryItem model, HttpPostedFileBase fileUpload) { var content = _context.Content.First(c => c.Id == model.ContentId); var pgi = new PhotoGalleryItem { Content = content }; TryUpdateModel(pgi, new[] { "Title", "Url" }); if (pgi.Url == null) { pgi.Url = ""; } if (fileUpload != null) { string fileName = IOHelper.GetUniqueFileName("~/Content/Images", fileUpload.FileName); string filePath = Server.MapPath("~/Content/Images"); filePath = Path.Combine(filePath, fileName); GraphicsHelper.SaveOriginalImage(filePath, fileName, fileUpload, 680); //fileUpload.SaveAs(filePath); pgi.ImageSource = fileName; } _context.PhotoGalleryItem.Add(pgi); _context.SaveChanges(); return RedirectToAction("Gallery", "Home", new { area = "", id = content.Name }); }
public ActionResult Answer([Bind(Include = "HomeworkId,Text,Date")] Answer answer, HttpPostedFileBase[] fileUpload) { if (ModelState.IsValid) { answer.Date = DateTime.Now; db.Answers.Add(answer); // Сохраняем файл в папку---------------------------------------------------- foreach (var file in fileUpload) { if (file == null) continue; var path = AppDomain.CurrentDomain.BaseDirectory + "UploadedAnswersFiles/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var filename = Path.GetFileName(file.FileName); if (filename != null) file.SaveAs(Path.Combine(path, filename)); var newPhoto = new AnswersPhoto { Name = file.FileName, Path = "/UploadedAnswersFiles/" + filename, // Нам не нужен путь на диске! Только относительный путь на сайте AnswerId = answer.Id }; db.AnswersPhotoList.Add(newPhoto); } // -------------------------------------------------------------------------- db.SaveChanges(); } return RedirectToAction("Index"); }
public void upload(System.Web.HttpPostedFileBase aFile) { string file = aFile.FileName; string path = Server.MapPath("../Upload//"); aFile.SaveAs(path + Guid.NewGuid() + "." + file.Split('.')[1]); }
public ActionResult Create(Student student, HttpPostedFileBase upload) { var db = DAL.DbContext.Create(); if (ModelState.IsValid) { if (StudentValidate(student)) { if (upload != null && upload.ContentLength > 0) { using (var reader = new System.IO.BinaryReader(upload.InputStream)) { student.Image = reader.ReadBytes(upload.ContentLength); } var studentId = db.Students.Insert(student); if (studentId.HasValue && studentId.Value > 0) { return RedirectToAction("Index"); } else { return View(student); } } } } //ViewBag.Id = new SelectList(db.GetCourses().Distinct().ToList(), "Id", "CourseAbbv"); ViewBag.CourseID = new SelectList(db.Courses.All(), "Id", "CourseAbbv", student.CourseID); ViewBag.CollegeID = new SelectList(db.Colleges.All(), "Id", "CollegeName", student.CollegeID); return View(student); }
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 AddImages(int id, HttpPostedFileBase file) { int intRes = 0; int idArticle = id; string imgNameResult = ""; foreach (string item in Request.Files) { if (file.ContentLength == 0) continue; if (file.ContentLength > 0) { ImageUpload imageUpload = new ImageUpload { Width = 800 }; ImageResult imageResult = imageUpload.RenameUploadFile(file); imgNameResult = imageResult.ImageName.ToString(); if (imageResult.Success) { string strModificador = "AMIGO"; DateTime FechaRegistro = DateTime.Now; //Guardar el Registro de la fotografía BRArticle oBRArticle = new BRArticle(); intRes = oBRArticle.SaveImageToArticle(idArticle, imgNameResult, strModificador); } } } return RedirectToAction("../home"); }
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); }
/// <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>"); }
public override System.Web.Mvc.ActionResult UploadInventory(System.Web.HttpPostedFileBase file) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.UploadInventory); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "file", file); UploadInventoryOverride(callInfo, file); return(callInfo); }
public override System.Web.Mvc.ActionResult FileUpload(System.Web.HttpPostedFileBase excelFile) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.FileUpload); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "excelFile", excelFile); FileUploadOverride(callInfo, excelFile); return(callInfo); }
public override System.Web.Mvc.ActionResult ChangeAvatar(System.Web.HttpPostedFileBase avatarFile) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.ChangeAvatar); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "avatarFile", avatarFile); ChangeAvatarOverride(callInfo, avatarFile); return(callInfo); }
public override System.Web.Mvc.ActionResult uploadFile(System.Web.HttpPostedFileBase PictureFile) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.uploadFile); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "PictureFile", PictureFile); uploadFileOverride(callInfo, PictureFile); return(callInfo); }
public ActionResult GarantiAdd(System.Web.HttpPostedFileBase PATH, FORMLINEGARANTI obj) { using (db) { int affectedRows = db.Execute("insert into "); } return(View()); }
public override System.Web.Mvc.ActionResult AdminRLUploadProvider(System.Web.HttpPostedFileBase ExcelFile) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.AdminRLUploadProvider); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "ExcelFile", ExcelFile); AdminRLUploadProviderOverride(callInfo, ExcelFile); return(callInfo); }
public override System.Web.Mvc.ActionResult Index(System.Web.HttpPostedFileBase FileUpload) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Index); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "FileUpload", FileUpload); IndexOverride(callInfo, FileUpload); return(callInfo); }
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); }
public override System.Web.Mvc.ActionResult Create(Models.Product product, System.Web.HttpPostedFileBase file) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Create); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "product", product); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "file", file); CreateOverride(callInfo, product, file); return(callInfo); }
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 override System.Web.Mvc.ActionResult UploadThumb(string path, System.Web.HttpPostedFileBase file) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.UploadThumb); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "path", path); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "file", file); UploadThumbOverride(callInfo, path, file); return(callInfo); }
public override System.Web.Mvc.ActionResult setPhoto(System.Web.HttpPostedFileBase Photo, int id) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.setPhoto); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "Photo", Photo); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "id", id); setPhotoOverride(callInfo, Photo, id); return(callInfo); }
public override System.Web.Mvc.ActionResult UploadPhoto(System.Web.HttpPostedFileBase profilePhoto, int usi) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.UploadPhoto); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "profilePhoto", profilePhoto); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "usi", usi); UploadPhotoOverride(callInfo, profilePhoto, usi); return(callInfo); }
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()); }
public JsonResult UploadGoodsImg() { byte[] byData = null; JsonResult result = null; tbClientUser clientuser = GetUser("UserInfo"); string RootFilePath = MYDZ.Business.StaticSystemConfig.soft.RootFilePath; try { System.Web.HttpPostedFileBase file = Request.Files["fileToUpload"]; if (file == null) { return(null); } if (file.ContentLength > 500 * 1024) { return(Json(new { URL = "", ErrorMsg = "大于500KB,上传失败!" })); } string hzm = file.FileName.Substring(file.FileName.LastIndexOf('.') + 1).ToLower(); if (hzm != "jpg" && hzm != "gif" && hzm != "png") { return(Json(new { URL = "", ErrorMsg = "选择的文件不是图片文件!" })); } using (Stream stream = file.InputStream) { byData = new Byte[stream.Length]; stream.Position = 0; stream.Read(byData, 0, byData.Length); stream.Close(); } string PictureCategoryName = "商品图片-魔云店长"; string cid = CheckPictureSpace(PictureCategoryName); if (cid == null) { return(null); } string errormsg = null; PictureUpload pu = new PictureUpload(); pu.ImageInputTitle = file.FileName; pu.PictureCategoryId = long.Parse(cid); pu.Img = byData; Picture picture = new Picture(); picture = sgi.PictureUpload(pu, clientuser.UserShops[0].SessionKey, out errormsg); if (errormsg == null) { result = Json(new { URL = picture.PicturePath, ErrorMsg = "" }); } } catch (Exception ex) { throw ex; } return(result); }
public string UploadLogo(System.Web.HttpPostedFileBase Filedata, string clienttype, string clientid) { try { WebImage img = WebImage.GetImageFromRequest(); if (img != null) { if (img.ImageFormat == "Bitmap") { Image bmp = null; Image converted = null; using (MemoryStream stream = new MemoryStream()) using (MemoryStream ms = new MemoryStream()) { ms.Write(img.GetBytes(), 0, img.GetBytes().Length); Image.FromStream(ms).Save(stream, ImageFormat.Png); converted = Image.FromStream(stream); } PictureManager.Instance.UploadRawImage(converted, clienttype + clientid, "resources", "employerlogos"); } else { PictureManager.Instance.UploadRawImage(img, clienttype + clientid, "resources", "employerlogos"); } } else { Image img2 = null; if (String.IsNullOrEmpty(Request["qqfile"])) { //This works with IE HttpPostedFileBase httpPostedFileBase = Request.Files[0] as HttpPostedFileBase; img2 = Image.FromStream(httpPostedFileBase.InputStream); } else { img2 = Image.FromStream(Request.InputStream); } PictureManager.Instance.UploadRawImage(img2, clienttype + clientid, "resources", "employerlogos"); } return("{\"success\":true}"); } catch { return("{\"error\":\"error\"}"); } }
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_ })); }
/// <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>"); }