public ActionResult ImageSave(ImageUpload obj) { try { //ImageUpload objTaskDetails = new ImageUpload(); HttpFileCollectionBase files = Request.Files; var x = ""; if (!string.IsNullOrEmpty(obj.ToString())) { for (int i = 0; i < files.Count; i++) { HttpPostedFileBase file = files[i]; byte[] ByteImgArray; ByteImgArray = ConvertToBytes(file); var ImageQuality = ConfigurationManager.AppSettings["ImageQuality"]; var reduceIMage = ReduceImageSize(ByteImgArray, ImageQuality); string fileName = file.FileName; x += fileName + ","; string serverMapPath = Server.MapPath("~/Images/"); string filePath = serverMapPath + "//" + fileName; SaveFile(reduceIMage, filePath, file.FileName); } obj.Image = x.Remove(x.Length - 1); _context.ImageUploads.Add(obj); _context.SaveChanges(); } } catch (Exception ex) { throw ex; } return(View("ImageUpload", obj)); }
public ActionResult Upload(ImageUploadViewModel formData) { var theseGuys = User.Identity.GetUserName(); var thisCouple = User.Identity.GetUserId(); var uploadedFile = Request.Files[0]; string filename = $"{DateTime.Now.Ticks}{uploadedFile.FileName}"; var serverPath = Server.MapPath(@"~\Uploads"); var fullPath = Path.Combine(serverPath, filename); //uploadedFile.SaveAs(fullPath); //resizing to 640x640 ResizeSettings resizeSetting = new ResizeSettings { Width = 640, Height = 640, Format = "png" }; ImageBuilder.Current.Build(uploadedFile, fullPath, resizeSetting); var uploadModel = new ImageUpload { Caption = theseGuys, File = filename }; var currentUser = db.Couples.Where(c => c.CurrentUser == thisCouple).FirstOrDefault(); currentUser.ProfilePic = uploadModel.Id; db.ImageUploads.Add(uploadModel); db.SaveChanges(); return(RedirectToAction("Browse", "Home")); }
public ActionResult Create([Bind(Include = "UserId,AuthorityId,UserName,Password,Email,Name,Images")] Users users, HttpPostedFileBase file) { if (ModelState.IsValid) { if (file != null) { ImageUpload imageUpload = new ImageUpload(); users.Images = imageUpload.ImageResizeUser(file, 240, 240); } else { ModelState.AddModelError("Fotoğraf", "Fotoğraf Eklemediniz"); } db.Users.Add(users); users.AuthorityId = 7; db.Users.Add(users); db.SaveChanges(); Session["UserId"] = users.UserId; Session["UserName"] = users.UserName; return(RedirectToAction("Index", "Home")); } return(View(users)); }
public async Task <IActionResult> Create([Bind("ImageID,ImagePath")] ImageUpload imageUpload) { if (ModelState.IsValid) { if (Request.Form.Files.Count > 0) { IFormFile file = Request.Form.Files.FirstOrDefault(); using (var dataStream = new MemoryStream()) { await file.CopyToAsync(dataStream); imageUpload.ImagePath = dataStream.ToArray(); imageUpload.FileName = file.FileName; } } else { return(RedirectToAction(nameof(Index))); } _context.Add(imageUpload); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(imageUpload)); }
[ValidateInput(false)]//ckeditör için html kod doğrulama isteği public ActionResult Edit([Bind(Include = "ProductId,CategoryId,Name,Price,Description,Image")] Products products, HttpPostedFileBase file, string editor1) { if (ModelState.IsValid) { ImageUpload imgUpload = new ImageUpload(); var product = db.Products.Find(products.ProductId); if (file != null) { //resim yükleme işlemi product.Image = imgUpload.ImageResize(file, 240, 240); } product.Categories = products.Categories; product.CategoryId = products.CategoryId; product.Description = editor1; product.Name = products.Name; product.Price = products.Price; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", products.CategoryId); return(View(products)); }
protected void UploadButton_Click(object sender, EventArgs e) { try { if (ImageUpload.HasFile) { if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlCommand cmd = new SqlCommand("EXEC USP_FeedBack @strCommand='ImageName'", conn); string filename = Convert.ToString(cmd.ExecuteScalar()); string ext = System.IO.Path.GetExtension(ImageUpload.PostedFile.FileName); // string filename = Path.GetFileName(ImageUpload.FileName); ImageUpload.SaveAs(Server.MapPath("~/FeedBackImage/") + filename + ext); lblImageName.Text = filename + ext; lblfile.Text = "Upload status: File uploaded"; lblfile.Visible = true; } else { lblfile.Visible = true; lblfile.Text = "Upload status: File not uploaded!"; } // mpeFeedBack.Show(); } catch (Exception ex) { lblfile.Visible = true; lblfile.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message; // mpeFeedBack.Show(); } }
public async Task <IActionResult> PutBook(int id, Book book) { if (id != book.ID) { return(BadRequest()); } if (book.CoverPhoto != null) { book.GUID = ImageUpload.WriteFile(book.FileName, book.CoverPhoto); //save new image to static folder book.CoverPhoto = null; book.FilePath = _config["ImagePath"] + book.GUID; } _DBContext.Entry(book).State = EntityState.Modified; try { await _DBContext.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BookExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
protected void Update_Btn(object sender, EventArgs e) { //파일 업로드 구문 시작 String savePath = @"C:\inetpub\wwwroot\ASP_Project2\Images\"; if (ImageUpload.HasFile) { string fileName = ImageUpload.FileName; // imgUp 에있는 파일평 따오기 savePath = savePath + fileName; // 지역변수 설정 ImageUpload.SaveAs(savePath); // 설정한 지역변수값 등록 } //파일 업로드 구문 끝 MySqlConnection connection = new MySqlConnection("Server=ec2-13-125-252-165.ap-northeast-2.compute.amazonaws.com;Database=2020Project;Uid=root;Pwd=qwer1234;"); connection.Open(); string UpdateQuery = "Update sellpost set title = @title , contents = @contents , image = @image where num = " + Request["No"]; MySqlCommand cmd = new MySqlCommand(UpdateQuery, connection); cmd.Parameters.AddWithValue("@title", title.Text); cmd.Parameters.AddWithValue("@contents", Contents.Text); cmd.Parameters.AddWithValue("@image", ImageUpload.FileName); cmd.ExecuteNonQuery(); connection.Close(); Response.Write("<script type='text/javascript'>window.history.go(-2);</script>"); }
public ActionResult ProductProcess(Product entity, HttpPostedFileBase file, string isNew) { if (file != null && file.ContentLength > 0 && file.ContentLength < 10485760) { ImageUpload imageUpload = new ImageUpload(); string imagePath = imageUpload.ImageResize(file, 673, 483); if (isNew != "true") { string filePath = Server.MapPath(entity.PictureUrl); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } } entity.PictureUrl = imagePath; } if (isNew == "true") { int addResult = proMng.Add(entity); } else { bool updateResult = proMng.Update(entity); } return(RedirectToAction("UrunIslemleri", "Product")); }
public static bool GenerateUser(User model, IUserService _userService, UserManager _manager, HttpServerUtilityBase server, User CurrentUser, DateTime currTime) { try { var path = server.MapPath("/UPLOADS/SubscriberFiles/" + CurrentUser.CompanyID); if (!PathChecker.IsExist(path)) { PathChecker.GenerateFolderOnPath(server.MapPath("/UPLOADS/SubscriberFiles"), CurrentUser.CompanyID); } var file = PathChecker.FindAvailableFileName(path, "File" + currTime.Date.ToString()); if (ImageUpload.UriToServer(model.ProfileImage, path + "/" + file)) { file = "/UPLOADS/SubscriberFiles/" + CurrentUser.CompanyID + "/" + file; model.ProfileImage = file; var newUser = new IdentityUser() { UserName = model.Email, Email = model.Email }; var aspResult = _manager.CreateAsync(newUser).Result; model.AspNetUserID = _userService.GetAllAsp().Result.Where(us => us.Email == model.Email).FirstOrDefault().Id; _manager.AddPassword(model.AspNetUserID, model.FirstName + DateTime.Now.Year); if (Insert(model, _userService)) { return(true); } } return(false); } catch { return(false); } }
public ActionResult Upload(ImageUploadViewModel formData) { var uploadedFile = Request.Files[0]; string filename = $"{DateTime.Now.Ticks}{uploadedFile.FileName}"; var serverPath = Server.MapPath(@"~\Uploads"); var fullPath = Path.Combine(serverPath, filename); //uploadedFile.SaveAs(fullPath); ResizeSettings resizeSetting = new ResizeSettings { Width = 640, Height = 640, Format = "png" }; ImageBuilder.Current.Build(uploadedFile, fullPath, resizeSetting); var uploadModel = new ImageUpload { Caption = User.Identity.GetUserName(), File = filename }; db.ImageUploads.Add(uploadModel); db.SaveChanges(); return(RedirectToAction("Index")); }
//Add a new product to the products xml protected void AddCake_Click(object sender, EventArgs e) { //Gets filename and path to save the image to var fileName = ImageUpload.FileName; var category = CategoryDropDown.SelectedItem.Value; if (fileName == "") { return; } var path = "~/Images/" + category + "/"; var tmp = path + fileName; decimal tmpDecimal = Convert.ToDecimal(txtBoxCakePrice.Text); //if ((tmpDecimal % 1) == 0) // txtBoxCakePrice.Text += ".00"; productUtil.AddProduct(txtBoxCakeName.Text, Convert.ToDecimal(txtBoxCakePrice.Text), txtBoxCakeDescription.Text, tmp, category); ImageUpload.SaveAs(Server.MapPath(path) + fileName); txtBoxCakeName.Text = ""; txtBoxCakePrice.Text = ""; txtBoxCakeDescription.Text = ""; Response.Redirect("Products.aspx"); }
//INSERTS datafields into Database Table protected void SubButton_Click(object sender, EventArgs e) { Call_Database callDB = new Call_Database(); if (ImageUpload.HasFile) { if (CheckFileType(ImageUpload.FileName)) { string strPath = "../Images/dbImages/" + ImageUpload.FileName; ImageUpload.SaveAs(MapPath(strPath)); } } if (NameBox.Text != "" && txtProfile.Text != "") { string Action = "DonorsINSERT"; callDB.FormINSERT(Action, NameBox.Text, ImageUpload.FileName, txtProfile.Text, null, null, 0, 0, 0, 0); NameBox.Text = String.Empty; txtProfile.Text = String.Empty; Call_Database update = new Call_Database(); RepeaterNum.DataSource = update.dbDonors; RepeaterNum.DataBind(); } }
/// <summary> /// 上传单张图片 /// </summary> /// <param name="hpf">上传控件HttpPostedFile</param> /// <param name="OldPath">原来图片地址</param> /// <param name="NewPath">新图片保存路径</param> /// <param name="IsDel">是否删除旧图</param> /// <param name="Size">图片大小(k),如:等于或小于0则默认为1024k</param> /// <returns>新图片地址</returns> public static string UpPicture(HttpPostedFile hpf, string OldPath, string NewPath, bool IsDel, int Size, out string errorStr) { if (Size <= 0) { Size = 1024; } string txtstr = string.Empty; errorStr = "0"; if (hpf.ContentLength > 0) { ImageUpload iu = new ImageUpload(); iu.FormFile = hpf; iu.OutFileName = ""; iu.MaxSize = 1024 * Size; iu.SavePath = @"~" + NewPath; iu.Upload(); if (iu.Error != 0) { switch (iu.Error) { case 1: errorStr = "没有上传的文件"; break; case 2: errorStr = "类型不允许"; break; case 3: errorStr = "大小超限"; break; case 4: errorStr = "未知错误"; break; } } else { //删除原来图片 if (IsDel && !string.IsNullOrEmpty(OldPath)) { string DUrl = System.Web.HttpContext.Current.Server.MapPath(@"~" + OldPath); if (File.Exists(DUrl)) { File.Delete(DUrl); } } } txtstr = NewPath + iu.OutFileName; } else { txtstr = OldPath; } return(txtstr); }
public void SendImageCreationMessage(ImageUpload upload) { //open Rabbit MQ Connection var factory = new ConnectionFactory { HostName = "localhost", UserName = "******", Password = "******", Port = AmqpTcpEndpoint.UseDefaultPort, VirtualHost = "/" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "ImageUpload", durable: false, exclusive: false, autoDelete: false, arguments: null); string message = JsonConvert.SerializeObject(upload); var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "", routingKey: "ImageUpload", basicProperties: null, body: body); } }
public void ScanImage(object source, ElapsedEventArgs eventArgs) { Debug.WriteLine("Monitor.ScanImage enter " + DateTime.Now); try { int screenWidth = Screen.GetBounds(new Point(0, 0)).Width; int screenHeight = Screen.GetBounds(new Point(0, 0)).Height; using (Bitmap screenShot = new Bitmap(screenWidth, screenHeight)) using (Graphics gfx = Graphics.FromImage(screenShot)) { gfx.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight)); ImageUpload image = new ImageUpload(); using (MemoryStream stream = new MemoryStream()) { screenShot.Save(stream, ImageFormat.Png); image.ImageData = stream.ToArray(); } image.UserID = Environment.UserName; image.CaptureTime = DateTime.Now.ToString(); new ScreenShotReceiverClient().Upload(image); } } catch (Exception e) { Debug.WriteLine(DateTime.Now); Debug.WriteLine(e); } Debug.WriteLine("Monitor.ScanImage exit " + DateTime.Now); Debug.Flush(); }
public ActionResult CategoryProcess(Category entity, HttpPostedFileBase file, string isNew) { if (file != null && file.ContentLength > 0 && file.ContentLength < 10485760) { string imagePath = new ImageUpload().ImageResize(file, 673, 483); if (isNew != "true") { string filePath = Server.MapPath(entity.PictureUrl); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } } entity.PictureUrl = imagePath; } if (isNew == "true") { int result = catMng.Add(entity); } else { bool updateResult = catMng.Update(entity); } return(RedirectToAction("Kategoriİslemleri", "Category")); }
protected void ImageUploadButton_Click(object sender, EventArgs e) { ImageUpload.SaveAs(Server.MapPath("~/UploadImage/" + ImageUpload.FileName)); UploadedImage.ImageUrl = "/UploadImage/" + ImageUpload.FileName; UploadedImage.AlternateText = ImageUpload.FileName; }
public ReadingPage() { BackgroundColor = Color.FromHex("#0b87a8"); var BackGroundImage_ = new ImageUpload("arkaplan") { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, }; var BooksGrid = new ExGrid(5, 2); for (int i = 0; i < 5; i++) { for (int j = 0; j < 2; j++) { var Book_ = new Book("ChildrenImagination") { TappedCommand = CallBook }; BooksGrid.Children.Add(Book_, j, i); } } var ScrollView_ = new ScrollView() { Content = BooksGrid }; var ContentGrid = new ExGrid(); ContentGrid.Children.Add(BackGroundImage_, 0, 0); ContentGrid.Children.Add(ScrollView_, 0, 0); Content = ContentGrid; }
public async Task <IActionResult> OnPost() { try { Post post = await _postMinion.GetAsync(ID ?? 0) ?? new Post(); post.Title = Post.Title; post.Author = Post.Author; post.Description = Post.Description; if (ImageUpload != null) { string tempFilePath = Path.GetTempFileName(); using (FileStream stream = new FileStream(tempFilePath, FileMode.Create)) { await ImageUpload.CopyToAsync(stream); } post.ImageUrl = await BlobRoss.UploadBlob("images", ImageUpload.FileName, tempFilePath); } await _postMinion.SaveAsync(post); return(RedirectToPage("/Posts/View", new { id = post.ID })); } catch (Exception e) { ViewData["ErrorMessage"] = e.Message; return(RedirectToPage("/Posts/View", new { id = ID })); } }
public IActionResult Post(ImageUpload upload) { ObjectResult output = StatusCode(401, error.NotLoggedIn); if (authProvider.IsLoggedIn) { string location = ""; string fileName = upload.File.FileName; cloudStorage.Connect(); string localFileLocation = $"{environment.WebRootPath}\\uploads\\{fileName}"; using (FileStream fs = System.IO.File.Create(localFileLocation)) { upload.File.CopyTo(fs); fs.Flush(); location = cloudStorage.UploadFile(fs); } System.IO.File.Delete(localFileLocation); imageDAL.AssignImageLocationToRecipe(location, new Recipe() { ID = Convert.ToInt32(upload.RecipeId) }); output = StatusCode(200, location); } return(output); }
public IActionResult UploadFileToSystemWebaction([FromForm] ImageUpload data) { try { var requestUrl = String.Format(Constants.WebactionsEndpoints.UploadFile, Constants.WebActionServerUrl, data.WebactionName, data.FileName); HttpContent fileStreamContent = new StreamContent(data.File.OpenReadStream()); var fileLink = ""; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", data.AuthId); using (var formData = new MultipartFormDataContent()) { formData.Add(fileStreamContent, "file", data.FileName); var response = client.PostAsync(requestUrl, formData).Result; if (response.IsSuccessStatusCode) { return(new JsonResult(response.Content.ReadAsStringAsync().Result)); } return(new JsonResult(fileLink)); } } } catch (Exception ex) { return(BadRequest(ex.ToString())); } }
public ActionResult AddLogo() { var uploadedFile = Request.Files[0]; string filename = $"{DateTime.Now.Ticks}{uploadedFile.FileName}"; var serverPath = Server.MapPath(@"~\Uploads"); var fullPath = Path.Combine(serverPath, filename); uploadedFile.SaveAs(fullPath); var image = new ImageUpload { File = filename, Type = "logo" }; db.Images.Add(image); var userId = User.Identity.GetUserId(); var bc = db.BarClients.SingleOrDefault(b => b.UserId == userId); var imagelog = new BarImageLog { BarImgUpId = image.Id, BarClientId = bc.Id, Timestamp = DateTime.Now }; db.BarImageLogs.Add(imagelog); db.SaveChanges(); return(RedirectToAction("Index")); }
public async Task <IActionResult> Edit(int id, [Bind("ImageID,ImagePath")] ImageUpload imageUpload) { if (id != imageUpload.ImageID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(imageUpload); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ImageUploadExists(imageUpload.ImageID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(imageUpload)); }
/// <summary> /// Upload product image with 2 size(large and small) /// </summary> /// <param name="file"></param> /// <param name="counter"></param> /// <returns></returns> public bool UploadProductImages(HttpPostedFileBase file, out string largeFileName, Int32 counter = 0) { try { ImageUpload largeImage = new ImageUpload { SavePath = DisplayProductConstants.LargeProductImageFolderPath }; ImageUpload smallImage = new ImageUpload { SavePath = DisplayProductConstants.SmallProductImageFolderPath }; var fileName = Path.GetFileName(file.FileName); string finalFileName = "ProductImage_" + ((counter).ToString()) + "_" + fileName; if (System.IO.File.Exists(HttpContext.Request.MapPath("~" + DisplayProductConstants.LargeProductImageFolderPath + finalFileName)) || System.IO.File.Exists(HttpContext.Request.MapPath("~" + DisplayProductConstants.SmallProductImageFolderPath + finalFileName))) { return(UploadProductImages(file, out largeFileName, ++counter)); } ImageResult uploadLargeImage = largeImage.UploadProductImage(file, finalFileName, 1000); ImageResult uploadSmallImage = smallImage.UploadProductImage(file, finalFileName, 700); largeFileName = uploadSmallImage.ImageName; return(true); } catch (Exception) { largeFileName = null; return(false); } }
public ActionResult Create([Bind(Include = "ProductId,BrandId,CategoryId,Name,Price,IsNew,IsSale,IsActive,ProductDetails")] Products products, HttpPostedFileBase file, string editor1, IEnumerable <HttpPostedFileBase> files) { if (ModelState.IsValid) { ImageUpload imageUpload = new ImageUpload(); if (file != null) { products.ImageURL = imageUpload.ImageResize(file, 255, 237); } products.ProductDetails.Description = editor1; products.RegisterDate = DateTime.Now; if (files.FirstOrDefault() != null) { foreach (var item in files) { var paths = imageUpload.ImageResize(item, 84, 84, 329, 380); products.ProductDetails.Images.Add(new Images { ImageURL = paths.Item1, ImageURLt = paths.Item2 }); } } db.Products.Add(products); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.BrandId = new SelectList(db.Brands, "BrandId", "Name", products.BrandId); ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", products.CategoryId); ViewBag.ProductId = new SelectList(db.ProductDetails, "ProductId", "Description", products.ProductId); return(View(products)); }
public ActionResult Create(CreateProductPostRequest productRequest) { productRequest.CreateBy = User.Identity.GetUserName(); if (User.IsInRole("Administrator")) { productRequest.Status = (int)Define.Status.Active; } else { productRequest.Status = (int)Define.Status.WaitingCreate; } if (ModelState.IsValid) { var file = Request.Files["coverImage"]; //HttpPostedFileBase file = coverImage; if (file != null && file.ContentLength > 0) { if (file.ContentLength > 0) { // width + height will force size, care for distortion //Exmaple: ImageUpload imageUpload = new ImageUpload { Width = 800, Height = 700 }; // height will increase the width proportionally //Example: ImageUpload imageUpload = new ImageUpload { Height= 600 }; // width will increase the height proportionally ImageUpload imageUpload = new ImageUpload { Width = 600 }; // rename, resize, and upload //return object that contains {bool Success,string ErrorMessage,string ImageName} ImageResult imageResult = imageUpload.RenameUploadFile(file); if (imageResult.Success) { // Add new image to database var photo = new share_Images { ImageName = imageResult.ImageName, ImagePath = Path.Combine(ImageUpload.LoadPath, imageResult.ImageName) }; var imageId = service.AddImage(photo); // Add product productRequest.CoverImageId = imageId; productRequest.CreateBy = User.Identity.GetUserName(); service.AddProduct(productRequest); return(RedirectToAction("Index")); } else { // use imageResult.ErrorMessage to show the error ViewBag.Error = imageResult.ErrorMessage; } } } } PopulateStatusDropDownList(); ViewBag.BrandId = PopulateListBrand(productRequest.BrandId); return(View("Create1", productRequest)); }
public async Task <bool> UploadImageToServer(ImageUpload imageUpload) { if (imageUpload != null) { try { string filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), imageUpload.FileName); NSData data = NSData.FromStream(App.FileHelper.GetStreamFromImageFile(filepath)); var image = UIImage.LoadFromData(data); PheidiParams pp = new PheidiParams(); pp.Add("NOSEQ", imageUpload.QueryFieldValue); pp.Add("FIELD", imageUpload.Field); bool success = await UploadImageToServer(image, imageUpload.FileName, filepath, pp, false); if (success) { if (File.Exists(filepath)) { File.Delete(filepath); } } return(success); } catch (Exception e) { Debug.WriteLine(e.Message); await DatabaseHelper.Database.DeleteItemAsync(imageUpload); } } return(false); }
protected void UploadButton_Click(object sender, EventArgs e) { if (EmptyCheck()) { string name = ImageUpload.FileName; string ipath = Server.MapPath(@"~\Images\") + name; ImageUpload.SaveAs(ipath); var movie = new Movie() { MovieTypeId = Convert.ToInt32(MovieTypeList.SelectedValue), MovieName = MovieNameBox.Text, Description = DescriptionBox.Text, Actor = ActorBox.Text, Image = @"~\Images\" + name, UploadDate = DateTime.Now, IsAudit = false }; var movieService = new MovieService(); var result = movieService.AddMovie(movie); if (result == 1) { Response.Redirect("MovieMaintenance.aspx"); } else { Response.Write("<script>alert('添加失败')</script>"); } } }
public ActionResult Create([Bind(Include = "SliderId,ImageUrl,RegisterDate")] Slider slider, IEnumerable <HttpPostedFileBase> files) { ImageUpload imageUpload = new ImageUpload(); if (ModelState.IsValid) { if (files.FirstOrDefault() != null) //ikinci olarak kontrol yazılır ÇOKLU image için { foreach (var item in files) { var image = imageUpload.ImageResize(item, 84, 84, 1140, 475); db.Slider.Add(new Slider { ImageUrl = image.Item1, RegisterDate = DateTime.Now }); } } db.SaveChanges(); return(RedirectToAction("Index")); } return(View(slider)); }
// 공지사항 게시글 수정 protected void Update_Btn(object sender, EventArgs e) { //파일 업로드 구문 시작 String savePath = @"C:\inetpub\wwwroot\ASP_Project2\Images\"; if (ImageUpload.HasFile) { string fileName = ImageUpload.FileName; // imgUp 에있는 파일평 따오기 savePath = savePath + fileName; // 지역변수 설정 ImageUpload.SaveAs(savePath); // 설정한 지역변수값 등록 } //파일 업로드 구문 끝 MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["mariadb"].ConnectionString); connection.Open(); string UpdateQuery = "Update notice set title = @title , contents = @contents , image = @image where num = " + Request["No"]; MySqlCommand cmd = new MySqlCommand(UpdateQuery, connection); cmd.Parameters.AddWithValue("@title", title.Text); cmd.Parameters.AddWithValue("@contents", Contents.Text); cmd.Parameters.AddWithValue("@image", ImageUpload.FileName); cmd.ExecuteNonQuery(); connection.Close(); Response.Write("<script type='text/javascript'>window.history.go(-2);</script>"); }