private void EditorFile(HttpContext context) { var iswater = context.Request.QueryString["IsWater"] == "1"; var imgFile = context.Request.Files["imgFile"]; if (imgFile == null) { ShowError(context, "请选择要上传文件!"); return; } var upload = new UploadUtility(); string remsg = upload.FileSaveAs(imgFile, false, iswater); JsonData jd = JsonMapper.ToObject(remsg); string status = jd["status"].ToString(); string msg = jd["msg"].ToString(); if (status == "0") { ShowError(context, msg); return; } string filePath = jd["path"].ToString(); //取得上传后的路径 var hash = new Hashtable(); hash["error"] = 0; hash["url"] = filePath; context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); context.Response.Write(JsonMapper.ToJson(hash)); context.Response.End(); }
public ActionResult Create(ArticleDto model) { if (ModelState.IsValid) { var file = Request.Files["ImageInput"]; if (file != null && file.ContentLength > 0) { var upload = new UploadUtility(StoreAreaForUpload.ForArticle); var result = upload.SharedCoverSaveAs(file); if (!result.Success) { ModelState.AddModelError("UploadError", result.Message); return(View(model)); } model.ThumbPath = result.Message; } else { const string noImage = @"/assets/img/bg/noarticle_photo_500x280.jpg"; model.ThumbPath = Utilities.GetImgUrl(model.ArticleContent); if (String.IsNullOrEmpty(model.ThumbPath)) { model.ThumbPath = noImage; } } _articleService.AddArticle(model); return(RedirectToAction("Index")); } return(View(model)); }
public OperationResult <ImageUrl> UploadImage(HttpPostedFileBase file, int blogId) { if (file.ContentLength > 0) { string fileName = DateTime.Now.ToString("yy/MM/dd/") + Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName); string diskPath = HttpContext.Current.Server.MapPath("~" + ConstValues.BlogImageDirectory + fileName); string diskDir = diskPath.Substring(0, diskPath.LastIndexOf("\\", StringComparison.Ordinal)); if (!Directory.Exists(diskDir)) { Directory.CreateDirectory(diskDir); } file.SaveAs(diskPath); string yunUrl = UploadUtility.UploadLocalFile(diskPath); var imageUrl = new ImageUrl() { BlogId = blogId, Url = fileName.Replace('/', '\\'), TimeStamp = DateTime.Now, YunUrl = yunUrl, ImageStatus = string.IsNullOrEmpty(yunUrl) ? ImageStatus.Local : ImageStatus.Yun }; _context.ImageUrls.Add(imageUrl); _context.SaveChanges(); if (string.IsNullOrEmpty(yunUrl)) { imageUrl.Url = "http://www.withyun.com" + ConstValues.BlogImageDirectory + fileName; } return(new OperationResult <ImageUrl>(true, imageUrl)); } return(new OperationResult <ImageUrl>(false, null)); }
private void OnUploadItemFinish(string file, string md5png) { uploadCounter++; var success = !string.IsNullOrEmpty(md5png); if (success) { var url = UploadUtility.GetDownloadFileUrl(md5png); Debug.Log("===上传完成>>" + url); if (thumbFiles.ContainsKey(file)) { thumbFiles[file] = url; } } else { uploadMsg = string.Format("上传至文件服务器失败!名称:{0}", Path.GetFileName(file)); } if (uploadCounter >= thumbFiles.Count) { thumbFiles.Values.ForEach(t => { if (t.IsNotNullAndEmpty()) { mUploadFiles.items.Add(t); } }); onFinish.InvokeGracefully(mUploadFiles, uploadMsg); } }
public ActionResult Edit([Bind(Include = "LessonID,LessonTitle,CourseID,Introduction,VideoURL,PdfFilename,IsActive")] Lesson lesson, HttpPostedFileBase lessonFile) { if (ModelState.IsValid) { #region File Upload if (lessonFile != null) { string file = lessonFile.FileName; string[] goodExts = new string[] { ".jpg", ".jpeg", ".png", ".gif", ".pdf" }; //check that the uploaded file ext is in our list of good file extensions && check file size <= 4mb (max by default from ASP.NET) if (goodExts.Contains(file.Substring(file.LastIndexOf("."))) && lessonFile.ContentLength <= 4194304) { if (lesson.PdfFilename != null && lesson.PdfFilename != "JustinLKennedyResume.pdf") //Delete the old file of the record that is being edited { string path = Server.MapPath("~/Content/images/lessons/"); UploadUtility.Delete(path, lesson.PdfFilename); } lessonFile.SaveAs(Server.MapPath("~/Content/images/lessons/" + file)); } lesson.PdfFilename = file; } #endregion db.Entry(lesson).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "CourseName", lesson.CourseID); return(View(lesson)); }
public async Task <IActionResult> Edit(int id, TVShowEditViewModel editModel) { TVshow tvshowFromDB = await _mediaWebDbContext.TVShows.FirstOrDefaultAsync(m => m.Id == id); List <string> tvshowTitlesFromDb = await _mediaWebDbContext.TVShows.Where(tv => tv != tvshowFromDB).Select(tvs => tvs.Name).ToListAsync(); if (tvshowTitlesFromDb.Contains(StringEdits.FirstLettterToUpper(editModel.Name))) { return(RedirectToAction("Index")); } tvshowFromDB.Name = editModel.Name; tvshowFromDB.ReleaseDate = editModel.ReleaseDate; tvshowFromDB.Summary = editModel.Summary; if (editModel.Picture != null) { tvshowFromDB.Picture = UploadUtility.UploadFile(editModel.Picture, "tvshows", _hostingEnvironment); } else { tvshowFromDB.Picture = editModel.PictureFile; } await _mediaWebDbContext.SaveChangesAsync(); return(RedirectToAction("Index")); }
private static ImageUrl DownloadBlogImgToLocal(string blogImgUrl) { ImageUrl imageUrl = new ImageUrl(); string fileName = CrawlerUtility.GetFileContent(blogImgUrl, Const.BlogFileDirectory, "http://www.zimuzu.tv/"); if (fileName == "") { return(null); } string localFilePath = Const.BlogFileDirectory + fileName; using (Image downloadImage = Image.FromFile(localFilePath)) { if (downloadImage.Size.Width > 500) { var image = Domain.Helper.ImgHandler.ZoomPictureProportionately(downloadImage, 500, 500 * downloadImage.Size.Height / downloadImage.Size.Width); image.Save(localFilePath); } } string yunUrl = UploadUtility.UploadLocalFile(localFilePath); Console.WriteLine("localFile:{0} upload to yunUrl:{1}", localFilePath, yunUrl); imageUrl.Url = fileName; imageUrl.ImageStatus = ImageStatus.Local; imageUrl.TimeStamp = DateTime.Now; if (!string.IsNullOrEmpty(yunUrl)) { imageUrl.YunUrl = yunUrl; imageUrl.ImageStatus = ImageStatus.Yun; } return(imageUrl); }
public MusicController(IWebHostEnvironment hostingEnvironment, MediaWebDbContext mediaWebDbContext, UserManager <MediaWebUser> userManager) { _hostingEnvironment = hostingEnvironment; _mediaWebDbContext = mediaWebDbContext; _uploadUtility = new UploadUtility(); _userManager = userManager; }
public ActionResult Edit([Bind(Include = "ActorId,ActorFirstName,ActorLastName,Address,City,State,ZipCode,PhoneNumber,AgencyID,ActorPhoto,SpecialNotes,DateAdded,IsActive")] Actor actor, HttpPostedFileBase actorheadshot) { if (ModelState.IsValid) { #region Image Upload if (actorheadshot != null) { /**/ string imgName = actorheadshot.FileName; /*1*/ string ext = imgName.Substring(imgName.LastIndexOf('.')); /*2*/ string[] goodExts = { ".jpeg", ".jpg", ".gif", ".png" }; /*3*/ if (goodExts.Contains(ext.ToLower()) && (actorheadshot.ContentLength <= 4193404)) { /*4*/ imgName = Guid.NewGuid() + ext.ToLower(); //commented this out and followed this other project file //actorheadshot.SaveAs(Server.MapPath("~/Content/actorheadshots/" + imgName)); #region Resize Image /*5*/ string savePath = Server.MapPath("~/Content/actorheadshots/"); //taking the contents of this file and creating a stream of bytes, http file base type is becoming a stream of bytes into a type of image. this conversion has to take place for us to be able to resize the image /*6*/ Image convertedImage = Image.FromStream(actorheadshot.InputStream); int maxImageSize = 500; int maxThumbSize = 100; //if you allowed image uploads for magazine and books - you would need to repeat that code - that's why the image service code is in an imageservice area /*7*/ UploadUtility.ResizeImage(savePath, imgName, convertedImage, maxImageSize, maxThumbSize); UploadUtility.Delete(savePath, actor.ActorPhoto); actor.ActorPhoto = imgName; //saves image onto server - but doesn't update db need to make sure to update what is stored in the db #endregion } else { imgName = "nouserimg.png"; } actor.ActorPhoto = imgName; } #endregion db.Entry(actor).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.AgencyID = new SelectList(db.UserDetails, "UserID", "FirstName", actor.AgencyID); return(View(actor)); }
public ActionResult Edit([Bind(Include = "UserID,FirstName,LastName,AgencyName,UserPhoto,UserNotes,DateFounded")] UserDetail userDetail, HttpPostedFileBase agencyphoto) { if (ModelState.IsValid) { if (agencyphoto != null) { string imgName = agencyphoto.FileName; string ext = imgName.Substring(imgName.LastIndexOf('.')); string[] goodExts = { ".jpeg", ".jpg", ".gif", ".png" }; if (goodExts.Contains(ext.ToLower()) && (agencyphoto.ContentLength <= 4193404)) { imgName = Guid.NewGuid() + ext.ToLower(); string savePath = Server.MapPath("~/Content/agencylogo/"); Image convertedImage = Image.FromStream(agencyphoto.InputStream); int maxImageSize = 500; int maxThumbSize = 100; UploadUtility.ResizeImage(savePath, imgName, convertedImage, maxImageSize, maxThumbSize); //UploadUtility.Delete(savePath, userDetail.UserPhoto); userDetail.UserPhoto = imgName; } else { imgName = "nouserimg.png"; } userDetail.UserPhoto = imgName; } db.Entry(userDetail).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(userDetail)); }
private void MultipleFile(HttpContext context) { var upFilePath = context.Request.QueryString["UpFilePath"]; var upfile = context.Request.Files[upFilePath]; var isWater = false; var isThumbnail = false; if (context.Request.QueryString["IsWater"] == "1") { isWater = true; } if (context.Request.QueryString["IsThumbnail"] == "1") { isThumbnail = true; } if (upfile == null) { context.Response.Write("{\"msg\": 0, \"msgbox\": \"请选择要上传文件!\"}"); return; } var upload = new UploadUtility(); var result = upload.FileSaveAs(upfile, isThumbnail, isWater, true); context.Response.Write(result); context.Response.End(); }
private static bool SaveRecomment(Blog blog, string coverImgUrl) { if (coverImgUrl == "") { return(true); } string fileName = CrawlerUtility.GetFileContent(coverImgUrl, Const.CoverFileDirectory, "http://www.zimuzu.tv/"); if (string.IsNullOrEmpty(fileName)) { return(true); } string localFilePath = Const.CoverFileDirectory + fileName; var image = Domain.Helper.ImgHandler.ZoomPicture(Image.FromFile(localFilePath), 200, 110); image.Save(localFilePath); string yunUrl = UploadUtility.UploadLocalFile(localFilePath); Console.WriteLine("localFile:{0} upload to yunUrl:{1}", localFilePath, yunUrl); var recomment = new Recomment() { BlogId = blog.Id, CoverName = fileName, Title = blog.Title, TimeStamp = DateTime.Now, Category = SetCategoryByTitle(blog.Title) }; if (!string.IsNullOrEmpty(yunUrl)) { recomment.YunUrl = yunUrl; recomment.ImageStatus = ImageStatus.Yun; } return(SyncUtility.SyncRecomment(recomment)); }
public ActionResult Create([Bind(Include = "OwnerAssetId,CarName,OwnerId,CarPhoto,SpecialNotes,IsActive,DateAdded")] Car car, HttpPostedFileBase CarPhoto) { #region File Upload if (ModelState.IsValid) { //Use default image if none is provided. string imgName = "GenericCar.jpg"; if (CarPhoto != null) //HttpPostedFileBase added to the action != null { //Get image and return to variable. imgName = CarPhoto.FileName; //Declare and assign ext variable. string ext = imgName.Substring(imgName.LastIndexOf('.')); //Declare a list of valid extensions. string[] goodExts = { ".jpeg", ".jpg", ".gif", ".png" }; //Check the ext variable (toLower()) against the valid list. if (goodExts.Contains(ext.ToLower()) && (CarPhoto.ContentLength <= 4194304))//Max 4MB value allowed by ASP.net { //If it is in the list using a guid imgName = Guid.NewGuid() + ext; //save to the webserver CarPhoto.SaveAs(Server.MapPath("~/Content/assets/img/" + imgName)); //Create variables to resize image. string savePath = Server.MapPath("~/Content/assets/img/"); Image convertedImage = Image.FromStream(CarPhoto.InputStream); int maxImgSize = 500; int maxThumbSize = 100; UploadUtility.ResizeImage(savePath, imgName, convertedImage, maxImgSize, maxThumbSize); } else { imgName = "GenericCar.jpg"; } //No matter what, add imgName to the object. car.CarPhoto = imgName; } } #endregion if (ModelState.IsValid) { db.Cars.Add(car); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.OwnerId = new SelectList(db.UserDetails, "UserId", "FirstName", car.OwnerId); return(View(car)); }
public static void TestUpload() { var filePath = SavePath + "/35/sticker_prefab_ppbbbmhmf_10_common.png"; UploadUtility.UploadFile(filePath, (res, msg) => { Debug.Log(UploadUtility.GetDownloadFileUrl(res)); }); }
private static bool SaveRecomment(Blog blog, string imageUrl, string category) { if (imageUrl == "") { return(true); } string fileName = CrawlerUtility.GetFileContent(imageUrl, Const.CoverFileDirectory, "http://www.mp4ba.com/"); if (fileName == "") { return(true); } var recomment = new Recomment() { BlogId = blog.Id, Title = blog.Title, CoverName = fileName, TimeStamp = DateTime.Now }; if (category.Contains("电影")) { recomment.Category = RecommentCategory.电影; } if (category.Contains("电视剧")) { recomment.Category = RecommentCategory.剧集; } if (category == "欧美电视剧") { recomment.Category = RecommentCategory.美剧; } if (category == "日韩电视剧") { recomment.Category = RecommentCategory.韩剧; } if (category == "综艺娱乐") { recomment.Category = RecommentCategory.综艺; } string localFilePath = Const.CoverFileDirectory + fileName; var image = Domain.Helper.ImgHandler.ZoomPicture(Image.FromFile(localFilePath), 200, 110); image.Save(localFilePath); string yunUrl = UploadUtility.UploadLocalFile(localFilePath); Console.WriteLine("localFile:{0} upload to yunUrl:{1}", localFilePath, yunUrl); if (!string.IsNullOrEmpty(yunUrl)) { recomment.YunUrl = yunUrl; recomment.ImageStatus = ImageStatus.Yun; } return(SyncUtility.SyncRecomment(recomment)); }
public ActionResult Edit([Bind(Include = "OwnerAssetId,CarName,OwnerId,CarPhoto,SpecialNotes,IsActive,DateAdded")] Car car, HttpPostedFileBase CarPhoto) { #region File Upload if (CarPhoto != null)//HttpPostedFileBase added to the action != null { //Get image and assign to variable string imgName = CarPhoto.FileName; //Declare and assign ext value string ext = imgName.Substring(imgName.LastIndexOf('.')); //Declare a list of valid extensions. string[] goodExts = { ".jpeg", ".jpg", ".gif", ".png" }; //Check the ext value (toLower()) against the valid list if (goodExts.Contains(ext.ToLower()) && (CarPhoto.ContentLength <= 4194304))//4MB max allowed by ASP.NET { //If it is in the list rename using a guid imgName = Guid.NewGuid() + ext; //Save to the webserver CarPhoto.SaveAs(Server.MapPath("~/Content/assets/img/" + imgName)); //Create variables to resize image. string savePath = Server.MapPath("~/Content/assets/img/"); Image convertedImage = Image.FromStream(CarPhoto.InputStream); int maxImgSize = 500; int maxThumbSize = 100; UploadUtility.ResizeImage(savePath, imgName, convertedImage, maxImgSize, maxThumbSize); //Make sure you are not deleting your default image. if (car.CarPhoto != null && car.CarPhoto != "GenericCar.jpg") { //Remove the original file string path = Server.MapPath("~/Content/assets/img/"); UploadUtility.Delete(path, car.CarPhoto); } //Only save if image meets criteria imageName to the object. car.CarPhoto = imgName; } } #endregion if (ModelState.IsValid) { db.Entry(car).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.OwnerId = new SelectList(db.UserDetails, "UserId", "FirstName", car.OwnerId); return(View(car)); }
public ActionResult Edit([Bind(Include = "HomeId,HomeName,Address,City,State,ZipCode,OwnderId,HomePhoto,SpecialNotes,IsActive,DateAdded")] Homes homes, HttpPostedFileBase homePhoto) { if (ModelState.IsValid) { #region File Upload if (homePhoto != null) { string file = homePhoto.FileName; //we need to make sure they are actually uploading an appropriate file type string ext = file.Substring(file.LastIndexOf('.')); string[] goodExts = { ".jpeg", ".jpg", ".png", ".gif" }; //check that the uploaded file is in our list of good file extensions if (goodExts.Contains(ext)) { //if valid ext, check file size <= 4mb (max by default from ASP.net) if (homePhoto.ContentLength <= 52428800) // specifying in bytes how big file can be { //create a new file name using a guid - a lot of users probably have images with the same names so we change it from what the user had to a guid Globally Unique Identifier file = Guid.NewGuid() + ext; #region Resize Image string savePath = Server.MapPath("~/Content/assets/img/Uploads/"); //taking the contents of this file and creatign a stream of bytes, http file base type is becmonig a stream of bytes into a type of image. this conversion has to take place for us to be able to resize the image Image convertedImage = Image.FromStream(homePhoto.InputStream); int maxImageSize = 500; int maxThumbSize = 100; //if you allowed image uploads for magazine and books - you would need to repeat that code - that's why the image service code is in an imageservice area UploadUtility.ResizeImage(savePath, file, convertedImage, maxImageSize, maxThumbSize); //saves image onto server - but doesn't update db need to make sure to update what is stored in the db #endregion if (homes.HomePhoto != null && homes.HomePhoto != "noimage.png") { string path = Server.MapPath("~/Content/assets/img/Uploads/"); UploadUtility.Delete(path, homes.HomePhoto); } } } homes.HomePhoto = file; } #endregion db.Entry(homes).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.OwnderId = new SelectList(db.UserDetails, "UserId", "CompanyName", homes.OwnderId); return(View(homes)); }
public ActionResult DeleteConfirmed(string id) { UserDetail userDetail = db.UserDetails.Find(id); if (userDetail.UserPhoto != null && userDetail.UserPhoto != "nouserimg.png") { UploadUtility.Delete(Server.MapPath("~/Content/agencylogo/"), userDetail.UserPhoto); } db.UserDetails.Remove(userDetail); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(int id) { Lesson lesson = db.Lessons.Find(id); //Delete the file of the record that is being removed if (lesson.PdfFilename != null) { string path = Server.MapPath("~/Content/images/lessons/"); UploadUtility.Delete(path, lesson.PdfFilename); } db.Lessons.Remove(lesson); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(int id) { Course course = db.Courses.Find(id); //Delete the image file of the record that is being removed if (course.CourseImage != null && course.CourseImage != "NoImage.png") { string path = Server.MapPath("~/Content/images/courses/"); UploadUtility.Delete(path, course.CourseImage); } db.Courses.Remove(course); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(int id) { Car car = db.Cars.Find(id); if (car.CarPhoto != null && car.CarPhoto != "GenericCar.jpg") { //Remove the original file from the edit view. string path = Server.MapPath("~/Content/assets/img/"); UploadUtility.Delete(path, car.CarPhoto); } db.Cars.Remove(car); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(int id) { Actor actor = db.Actors.Find(id); #region Image utility if (actor.ActorPhoto != null && actor.ActorPhoto != "nouserimg.png") { UploadUtility.Delete(Server.MapPath("~/Content/actorheadshots/"), actor.ActorPhoto); } #endregion db.Actors.Remove(actor); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(int id) { AuditionLocation auditionLocation = db.AuditionLocations.Find(id); #region Image utility if (auditionLocation.AuditionPhoto != null && auditionLocation.AuditionPhoto != "nouserimg.png") { UploadUtility.Delete(Server.MapPath("~/Content/auditionlocations/"), auditionLocation.AuditionPhoto); } #endregion db.AuditionLocations.Remove(auditionLocation); db.SaveChanges(); return(RedirectToAction("Index")); }
private static bool SaveRecomment(Blog blog, string imageUrl, string category) { if (imageUrl == "http://verycd.gdajie.com/img/default_cover.jpg" || imageUrl == "") { return(true); } string fileName = CrawlerUtility.GetFileContent(imageUrl, Const.CoverFileDirectory, "http://www.gdajie.com/"); if (string.IsNullOrEmpty(fileName)) { return(true); } string localFilePath = Const.CoverFileDirectory + fileName; try { using (var localImage = Image.FromFile(localFilePath)) { var image = ImgHandler.ZoomPicture(localImage, 200, 110); image.Save(localFilePath); } } catch (Exception ex) { Logger.Error(ex, "localFilePath:{0}", localFilePath); return(true); } string yunUrl = UploadUtility.UploadLocalFile(localFilePath); Info("localFile:{0} upload to yunUrl:{1}", localFilePath, yunUrl); var recomment = new Recomment() { BlogId = blog.Id, CoverName = fileName, Title = blog.Title, TimeStamp = DateTime.Now, Category = SetCategory(category) }; if (!string.IsNullOrEmpty(yunUrl)) { recomment.YunUrl = yunUrl; recomment.ImageStatus = ImageStatus.Yun; } return(SyncUtility.SyncRecomment(recomment)); }
public ActionResult Create([Bind(Include = "PhotoID,Title,PhotoUrl,FilterID,OwnerAssetID")] Photo photo, HttpPostedFileBase myImg) { if (ModelState.IsValid) { #region PhotoUpload string imageName = "noImage.png"; if (myImg != null) { //Get File Extension - alternative to using a Substring () and Indexof() string imgExt = System.IO.Path.GetExtension(myImg.FileName); //list of allowed extentions string[] allowedExtentions = { ".png", ".gif", ".jpg", ".jpeg" }; if (allowedExtentions.Contains(imgExt.ToLower()) && (myImg.ContentLength <= 4194304)) { //using GUid for saved file name imageName = Guid.NewGuid() + imgExt; //creat some variables to pass to the resize image method //Signature to resize Image string savePath = Server.MapPath("~/Content/assets/img/portfolio/"); Image convertedImage = Image.FromStream(myImg.InputStream); int maxImgSize = 1200; int maxThumbSize = 100; //calling this method will use the variables created above will save the full size image and thumbnail img to your server. UploadUtility.ResizeImage(savePath, imageName, convertedImage, maxImgSize, maxThumbSize); ViewBag.PhotoMessage = "Photo Upload Complete."; } else { imageName = "noImage.png"; } photo.PhotoUrl = imageName; } #endregion db.Photos.Add(photo); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.FilterID = new SelectList(db.Filters, "FilterID", "FilterName", photo.FilterID); ViewBag.OwnerAssetID = new SelectList(db.OwnerAssets, "OwnerAssetID", "AssetCallName", photo.OwnerAssetID); return(View(photo)); }
public ActionResult Create([Bind(Include = "OwnerAssetID,AssetRegisteredName,AssetCallName,AssetSpecies,AssetBreed,AssetAge,AssetSize,AssetTrainerCertified,UserID,AssetPhoto,SpecialNotes,IsActive,DateAdded,DescriptiveColorProfile")] OwnerAsset ownerAsset, HttpPostedFileBase myImg) { if (ModelState.IsValid) { #region PhotoUpload string imageName = "noImage.png"; if (myImg != null) { //Get File Extension - alternative to using a Substring () and Indexof() string imgExt = System.IO.Path.GetExtension(myImg.FileName); //list of allowed extentions string[] allowedExtentions = { ".png", ".gif", ".jpg", ".jpeg" }; if (allowedExtentions.Contains(imgExt.ToLower()) && (myImg.ContentLength <= 4194304)) { //using GUid for saved file name imageName = Guid.NewGuid() + imgExt; //creat some variables to pass to the resize image method //Signature to resize Image string savePath = Server.MapPath("~/Content/assets/Image/"); Image convertedImage = Image.FromStream(myImg.InputStream); int maxImgSize = 1200; int maxThumbSize = 100; //calling this method will use the variables created above will save the full size image and thumbnail img to your server. UploadUtility.ResizeImage(savePath, imageName, convertedImage, maxImgSize, maxThumbSize); ViewBag.PhotoMessage = "Photo Upload Complete."; } else { imageName = "noImage.png"; } ownerAsset.AssetPhoto = imageName; } #endregion db.OwnerAssets.Add(ownerAsset); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.UserID = new SelectList(db.OwnerInformations, "UserID", "FullName", ownerAsset.UserID); return(View(ownerAsset)); }
private IEnumerator UploadFiles() { RenderThumbMgr.ReportSegTime(5, "ToUpload"); if (thumbFiles.Count == 0) { onFinish.InvokeGracefully(null, "待渲染零件个数为0"); yield break; } uploadCounter = 0; mUploadFiles = new UploadFiles(); uploadMsg = string.Empty; foreach (var file in thumbFiles.Keys) { UploadUtility.UploadFile(file, OnUploadItemFinish); yield return(null); } }
public ActionResult Edit([Bind(Include = "CourseID,CourseName,CourseDescription,CourseImage,IsActive")] Course course, HttpPostedFileBase courseImage) { if (ModelState.IsValid) { #region File Upload if (courseImage != null) { string file = courseImage.FileName; string ext = file.Substring(file.LastIndexOf('.')); string[] goodExts = { ".jpeg", ".jpg", ".png", ".gif" }; //check that the uploaded file ext is in our list of good file extensions if (goodExts.Contains(ext)) { //if valid ext, check file size <= 4mb (max by default from ASP.NET) if (courseImage.ContentLength <= 4194304) { //create a new file name using a guid //file = Guid.NewGuid() + ext; #region Resize Image string savePath = Server.MapPath("~/Content/images/courses/"); Image convertedImage = Image.FromStream(courseImage.InputStream); int maxImageSize = 800; int maxThumbSize = 350; UploadUtility.ResizeImage(savePath, file, convertedImage, maxImageSize, maxThumbSize); #endregion if (course.CourseImage != null && course.CourseImage != "NoImage.png") { string path = Server.MapPath("~/Content/images/courses/"); UploadUtility.Delete(path, course.CourseImage); } } } course.CourseImage = file; } #endregion db.Entry(course).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(course)); }
public ActionResult Receive(HttpPostedFileBase fileData, string atlasId) { var remark = String.Empty; if (String.IsNullOrEmpty(atlasId)) { remark = @"图册编号为空,请确认后再提交"; var data = new { state = false, description = remark }; return(Json(data)); } if (fileData != null && fileData.ContentLength > 0) { var atlasGuid = new Guid(atlasId); var temp = _atlasService.GetAtlasById(atlasGuid); if (temp == null) { remark = String.Format("未能根据编号[{0}]找到该分享图册", atlasId); var data = new { state = false, description = remark }; return(Json(data)); } const bool isWater = false; const bool isThumbnail = true; var upload = new UploadUtility(StoreAreaForUpload.ForGallery); var photoDto = upload.PictureSaveAs(fileData, isThumbnail, isWater, false); if (photoDto.PhotoId == Guid.Empty) { var data = new { state = false, description = photoDto.Remark }; return(Json(data, JsonRequestBehavior.AllowGet)); } photoDto.AtlasId = atlasGuid; photoDto.Remark = @"暂无描述..."; _photoService.AddPhoto(photoDto); var result = new { state = true, item = photoDto }; return(Json(result, JsonRequestBehavior.AllowGet)); } var error = new { state = false, description = @"无上传的图片" }; return(Json(error, JsonRequestBehavior.AllowGet)); }
public async Task <IActionResult> Edit(int id, PodcastEditViewModel editModel) { PodCast podcastFromDb = await _mediaWebDbContext.PodCasts.FirstOrDefaultAsync(m => m.Id == id); List <string> podcastTitlesFromDb = await _mediaWebDbContext.PodCasts.Where(podcast => podcast != podcastFromDb).Select(p => p.Title).ToListAsync(); if (podcastTitlesFromDb.Contains(StringEdits.FirstLettterToUpper(editModel.Title))) { return(RedirectToAction("index")); } podcastFromDb.Title = editModel.Title; podcastFromDb.ReleaseDate = editModel.ReleaseDate; podcastFromDb.Description = editModel.Description; podcastFromDb.File = UploadUtility.UploadFile(editModel.Podcast, "podcasts", _hostingEnvironment); await _mediaWebDbContext.SaveChangesAsync(); return(RedirectToAction("Index")); }