public ActionResult Edit(Image model, HttpPostedFileBase newImage) { if (ModelState.IsValid) { var image = db.Images.Find(model.ID); if (image == null) { return(new HttpNotFoundResult()); } // S3 credentials var s3BktName = ConfigurationManager.AppSettings["S3BucketName"]; var s3AccessKey = ConfigurationManager.AppSettings["AWSAccessKeyId"]; var s3SecretAccessKey = ConfigurationManager.AppSettings["AWSSecretAccessKey"]; var s3Region = ConfigurationManager.AppSettings["AWSRegion"]; var s3FolderName = "Test"; var s3ObjectKey = s3FolderName + "/" + Path.GetFileName(newImage.FileName); var awsS3Helper = new AwsS3Helper(); if (awsS3Helper.ConnectS3(s3AccessKey, s3SecretAccessKey, s3Region)) { // Delete the existing image first awsS3Helper.DeleteS3Object(image.ImagePathS3, s3BktName, null); awsS3Helper.UploadS3File(s3ObjectKey, s3BktName, newImage.ContentType, newImage.InputStream); } string filePath = GetPartialFilePath(newImage); var oldImagePath = image.ImagePath; // Saving in DB image.ImageTitle = Path.GetFileNameWithoutExtension(newImage.FileName); image.ImagePath = filePath; image.ImagePathS3 = s3ObjectKey; image.OriginalFileName = Path.GetFileName(newImage.FileName); db.Entry(image).State = EntityState.Modified; db.SaveChanges(); // Delete existing file string sFName = HttpContext.Server.MapPath(oldImagePath); System.IO.File.Delete(sFName); // Saving in physical location filePath = Server.MapPath(filePath); newImage.SaveAs(filePath); return(RedirectToAction("Index")); } return(View()); }
public JsonResult Create(string additionInfo) { if (Request.Files.Count > 0) { // S3 credentials var s3BktName = ConfigurationManager.AppSettings["S3BucketName"]; var s3AccessKey = ConfigurationManager.AppSettings["AWSAccessKeyId"]; var s3SecretAccessKey = ConfigurationManager.AppSettings["AWSSecretAccessKey"]; var s3Region = ConfigurationManager.AppSettings["AWSRegion"]; var s3FolderName = "Test"; var s3ObjectKey = s3FolderName + "/"; var awsS3Helper = new AwsS3Helper(); var s3Connected = awsS3Helper.ConnectS3(s3AccessKey, s3SecretAccessKey, s3Region) && awsS3Helper.CreateFolder(s3BktName, s3FolderName); // Get all files from Request object HttpFileCollectionBase files = Request.Files; for (int i = 0; i < files.Count; i++) { HttpPostedFileBase file = files[i]; // Saving S3 if (s3Connected) { s3ObjectKey += Path.GetFileName(file.FileName); awsS3Helper.UploadS3File(s3ObjectKey, s3BktName, file.ContentType, file.InputStream); } string filePath = GetPartialFilePath(file); //Adding database Entry var image = new Image { ImageTitle = Path.GetFileNameWithoutExtension(file.FileName), ImagePath = filePath, ImagePathS3 = s3ObjectKey, OriginalFileName = Path.GetFileName(file.FileName) }; db.Images.Add(image); filePath = Server.MapPath(filePath); file.SaveAs(filePath); } db.SaveChanges(); return(Json(new { Message = "Images uploaded successfully." })); } return(Json(new { Message = "Please select atleast image first." })); }