Upload multiple images and convert to base64 before saving to database - c#

I got a form which permits to upload multiple images. I then collect these images, upload them to a file in the app and convert them to base64 strings before saving the strings to the database.
Below is what I got already :
View :
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-4 ">
<div class="form-group">
#Html.LabelFor(Model => Model.VueSiegeArriere, new { #class = "control-label", })
#Html.TextBoxFor(Model => Model.VueSiegeArriere, new { #class = "form-control", type = "file", accept = "image/x-png,image/jpeg", id = "VueSiegeArriere" })
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-4 ">
<div class="form-group">
#Html.LabelFor(Model => Model.VueSiegeAvant, new { #class = "control-label", })
#Html.TextBoxFor(Model => Model.VueSiegeAvant, new { #class = "form-control", type = "file", accept = "image/x-png,image/jpeg", id = "VueSiegeAvant" })
</div>
</div>
Controller:
[HttpPost]
public ActionResult AddVoiture(VoitureVM v, HttpPostedFileBase VueFace, HttpPostedFileBase VueArriere, HttpPostedFileBase VueGauche, HttpPostedFileBase VueDroite, HttpPostedFileBase VueSiegeArriere, HttpPostedFileBase VueSiegeAvant, HttpPostedFileBase MalleArriere, HttpPostedFileBase TableauBord)
{
Voiture Car = new Voiture();
v.VueFace = UploadandConvertImage(VueFace);
v.VueGauche = UploadandConvertImage(VueGauche);
v.VueSiegeArriere = UploadandConvertImage(VueSiegeArriere);
v.VueSiegeAvant = UploadandConvertImage(VueSiegeAvant);
v.VueDroite = UploadandConvertImage(VueDroite);
v.TableauBord = UploadandConvertImage(TableauBord);
v.VueArriere = UploadandConvertImage(VueArriere);
v.MalleArriere = UploadandConvertImage(MalleArriere);
return RedirectToAction("Liste");
//return View(v);
}
UploadandConvertImage method which I call in the controller:
string base64String;
private string UploadandConvertImage(HttpPostedFileBase file)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("~/Pictures/Voitures"), pic);
// file is uploaded
file.SaveAs(path);
//wish to convert the uploaded images to base64 and store them in database
using (System.Drawing.Image image = System.Drawing.Image.FromFile(path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
base64String = Convert.ToBase64String(imageBytes);
//return base64String;
}
}
}
return base64String;
}
Saving to database :
//Let's now insert details into the table ImagesVoitures
ImagesVoiture carImages = new ImagesVoiture();
carImages.VueFace = voiture.VueFace;
carImages.VueGauche = voiture.VueGauche;
carImages.VueDroite = voiture.VueDroite;
carImages.VueSiegeArriere = voiture.VueSiegeArriere;
carImages.VueSiegeAvant = voiture.VueSiegeAvant;
carImages.TableauBord = voiture.TableauBord;
carImages.MalleArriere = voiture.MalleArriere;
carImages.VueArriere = voiture.VueArriere;
bdd.ImagesVoiture.Add(carImages);
bdd.SaveChanges();
What I expect to get are the base64 strings which I can save to the respective fields in the database.
What I actually get is an SQLException which says :
System.Data.Entity.Validation.DbEntityValidationException : 'Échec de
la validation d'une ou de plusieurs entités. Pour plus d'informations,
consultez 'EntityValidationErrors'.'

Your error is not coming from the code you've posted. In this code I don't see that you're saving to a database either.
It looks like your Voiture model has validation on it. The strings you are assigning to the car instance of Voiture are probably not passing validation.
I may be making a mistake, but it looks like you're posting images, turning them to base64 strings and returning them back to the client or view.
Did I miss something?

Related

The uploaded file value gets deleted once the page is re-submitted with incomplete inputs

I would like the page to saves the uploaded file even if the submit button is clicked at the time where not all the form is filled unless all the form is completed.
<div class="form-group">
#Html.LabelFor(model => model.cvURL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-lg-10">
#Html.TextBoxFor(model => model.cvURL, new { type = "file" })
#Html.ValidationMessageFor(model => model.cvURL)
</div>
</div>
public ActionResult RegisterCandidates(CandidateRegisteration can, HttpPostedFileBase cvURL)
{
if (ModelState.IsValid)
{
if (CheckFileType(cvURL.FileName))
{
var fileName = Path.GetFileName(cvURL.FileName);
var path = Path.Combine(Server.MapPath("~/CVuploads"), fileName);
can.cvURL = cvURL.FileName;
cvURL.SaveAs(path);
db.CandidateRegisteration.Add(can);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
ViewBag.emailExists = "Not Right extention";
}
}
return View();
}

Problem about uploading image to database in ASP.Net MVC

I am trying to upload images to database in MVC. There is not any error while uploading but then looks NULL in database.
Create.cshtml
<div class="form-group">
#Html.LabelFor(model => model.Foto, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="ImageData" id="ImageData" />
</div>
</div>
[HttpPost]
public ActionResult MakaleOlustur(Makale m, HttpPostedFileBase file)
{
try
{
using (MvcBlogContext context = new MvcBlogContext())
{
Makale _makale = new Makale();
if (file != null && file.ContentLength > 0)
{
MemoryStream memoryStream = file.InputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
file.InputStream.CopyTo(memoryStream);
}
_makale.Foto = memoryStream.ToArray();
}
_makale.Baslik = m.Baslik;
_makale.OlusturmaTarihi = DateTime.Now;
_makale.Icerik = m.Icerik;
context.Makale.Add(_makale);
context.SaveChanges();
return RedirectToAction("Makale", "Admin");
}
}
catch (Exception ex)
{
throw new Exception("Eklerken hata oluştu" + ex.Message);
}
}
Interestingly, this exactly same codes work in another project. Can you help me?

Getting Same Image from Three upload controls in one view MVC

I have three file upload control, All accepts single file but when i am getting in view all are saving as same image in my image folder -
my model is below in model i took HttpPostedFileBase type three variables and three label variable:
[NotMapped]
[DisplayName("Upload Image")]
public string ImagePath { get; set; }
[NotMapped]
public HttpPostedFileBase ImageFile { get; set; }
[NotMapped]
[DisplayName("Upload Aadhaar Card")]
public string AadhaarPathL { get; set; }
[NotMapped]
public HttpPostedFileBase AadhaarFile{get;set;}
[NotMapped]
[DisplayName("Upload PAN Card")]
public string PanPathL { get; set; }
[NotMapped]
public HttpPostedFileBase PanFile { get; set; }
In View i declared file type text bos for uploading the image :
#using (Html.BeginForm("CreateVendor", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div style="margin-left:70px;">
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.ImagePath)
#Html.TextBoxFor(model => model.ImageFile, new { type = "file", name = "ImageFile", id = "ImageFile",#class= "form-control" })
#Html.ValidationMessageFor(model => model.ImagePath, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.AadhaarPathL)
#Html.TextBoxFor(m => m.AadhaarFile,new { type = "file", name = "AadhaarFile", id = "AadhaarFile", #class = "form-control" })
#Html.ValidationMessageFor(model => model.AadhaarPathL, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.PanPathL)
#Html.TextBoxFor(m => m.PanFile, new { type = "file", name = "PanFile", id = "PanFile", #class = "form-control" })
#Html.ValidationMessageFor(model => model.PanPathL, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#* Empty *#
</div>
</div>
</div>
</div>
}
And finally in View code i am getting one by one both uri and image but everytime i am getting saved same image for every image . i am stucked here
[HttpPost]
public ActionResult CreateVendor(VendorList vendorList)
{
#region Photo Image
string fileName = Path.GetFileNameWithoutExtension(vendorList.ImageFile.FileName);
string extension = Path.GetExtension(vendorList.ImageFile.FileName);
fileName = fileName + "Photo" + DateTime.Now.ToString("yymmssfff") + extension;
var uri = string.Format("{0}://{1}{2}{3}",
System.Web.HttpContext.Current.Request.Url.Scheme,
System.Web.HttpContext.Current.Request.Url.Host,
System.Web.HttpContext.Current.Request.Url.Port == 80 ? string.Empty : ":" + System.Web.HttpContext.Current.Request.Url.Port,
"/Image/" + fileName);
vendorList.ImagePath = "~/Image/" + fileName;
fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
vendorList.ImageFile.SaveAs(fileName);
vendorList.PhotoPath = fileName;
vendorList.PhotoUrl = uri;
#endregion
#region Aadhaar Image
string fileAadhaarName = Path.GetFileNameWithoutExtension(vendorList.AadhaarFile.FileName);
string extensionAadhaar = Path.GetExtension(vendorList.AadhaarFile.FileName);
fileAadhaarName = fileAadhaarName + vendorList.Email + "Aadhaar" + DateTime.Now.ToString("yymmssfff") + extensionAadhaar;
var uriAadhaar = string.Format("{0}://{1}{2}{3}",
System.Web.HttpContext.Current.Request.Url.Scheme,
System.Web.HttpContext.Current.Request.Url.Host,
System.Web.HttpContext.Current.Request.Url.Port == 80 ? string.Empty : ":" + System.Web.HttpContext.Current.Request.Url.Port,
"/Image/" + fileAadhaarName);
vendorList.AadhaarPathL = "~/Image/" + fileAadhaarName;
fileAadhaarName = Path.Combine(Server.MapPath("~/Image/"), fileAadhaarName);
vendorList.ImageFile.SaveAs(fileAadhaarName);
vendorList.AadhaarPath = fileAadhaarName;
vendorList.AadhaarUrl = uriAadhaar;
#endregion
#region Pan Image
string filePanName = Path.GetFileNameWithoutExtension(vendorList.PanFile.FileName);
string extensionPan = Path.GetExtension(vendorList.PanFile.FileName);
filePanName = filePanName + vendorList.Email + "Pan" + DateTime.Now.ToString("yymmssfff") + extensionPan;
var uriPan = string.Format("{0}://{1}{2}{3}",
System.Web.HttpContext.Current.Request.Url.Scheme,
System.Web.HttpContext.Current.Request.Url.Host,
System.Web.HttpContext.Current.Request.Url.Port == 80 ? string.Empty : ":" + System.Web.HttpContext.Current.Request.Url.Port,
"/Image/" + filePanName);
vendorList.PanPathL = "~/Image/" + filePanName;
filePanName = Path.Combine(Server.MapPath("~/Image/"), filePanName);
vendorList.ImageFile.SaveAs(filePanName);
vendorList.PanPath = filePanName;
vendorList.PanUrl = uriPan;
}
Can someone suggest what is happening here .

Asp.NET MVC -- Fileupload image value shows null values in httppost method

I have a MultipartForms in Which I Could upload an Image and other form values.While, the form values are rightfully received through the FormCollection Property whereas the Upload file always shows the null value in HttpPostedFileBase Property.I go through forums but I couldn't get Where went Wrong. Here, Is What I done Please go through it and Said what Went Wrong.Thanks friend.
enter code here
cshtml:
#using (Html.BeginForm("Create", "StaffRegistration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="StaffImage" id="StaffImage" />
}
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection,HttpPostedFileBase File)
{
try
{
// TODO: Add insert logic here
StaffRegistration StaffReg = new StaffRegistration();
StaffReg.FirstName = collection["FirstName"].ToString();
StaffReg.LastName = collection["LastName"].ToString();
StaffReg.DateOfBirth = DateTime.Parse(collection["DateofBirth"]);
StaffReg.Nationality = collection["Nationality"].ToString();
StaffReg.Gender = collection["Gender"].ToString();
StaffReg.MaritalStatus = collection["MaritalStatus"].ToString();
StaffReg.BloodGroup = collection["BloodGroup"].ToString();
StaffReg.StaffName = collection["StaffName"].ToString();
StaffReg.MiddleName = collection["MiddleName"].ToString();
HttpPostedFileBase file = Request.Files["StaffImage"];
StaffRegistrationBusSer StaffRegBusSer = new StaffRegistrationBusSer();
StaffRegBusSer.AddStaffReg(StaffReg,file);
return RedirectToAction("Index");
}
DataLayer
public bool AddStaffRegistraiton(StaffRegistration staffRegistration,HttpPostedFileBase File)
{
staffRegistration.StaffImage = ConvertToByte(File);
using(SqlConnection Con = new SqlConnection(ConnectionString))
{
SqlParameter paramImage = new SqlParameter();
paramImage.ParameterName = "#StaffImage";
paramImage.Value = staffRegistration.StaffImage;
Cmd.Parameters.Add(paramImage);
Con.Open();
Cmd.ExecuteNonQuery();
}
return true;
}
ConvertToByte function:
public byte[] ConvertToByte(HttpPostedFileBase Image)
{
byte[] imagebyte = null;
BinaryReader Reader = new BinaryReader(Image.InputStream);
imagebyte = Reader.ReadBytes((int)Image.ContentLength);
return imagebyte;
}
cshtml page:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
#Html.LabelFor(model => model.StaffName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StaffName)
#Html.ValidationMessageFor(model => model.StaffName)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="file" name="StaffImage" id="StaffImage" />
</div>
</div>
}
Actually I have to include multipart/form in View level, Instead of the particular upload files.Then, I Modified like this in .cshtml page. Now, my code works fine

EF7 MVC ASP.NET File upload in form

I'm trying to upload a file alongside with some model information.
In my table I already have a field 'image' (string) to save the relative URL to the image.
But I don't really know how to do the uploading itself.
I've already read a lot off tutorials, but they all use HttpPostedFileBase, which isn't supported anymore?
This is what I have thus far:
Upload page:
#using (Html.BeginForm("Lets", "Create", FormMethod.Post, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<fieldset>
<div class="form-group">
<div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
#Html.LabelFor(m => m.Lets.Name, new { #class="mdl-textfield__label" })
#Html.TextBoxFor(m => m.Lets.Name, new { #class= "form-control mdl-textfield__input" })
</div>
</div>
<div class="form-group">
<div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
#Html.LabelFor(m => m.Lets.Images)
<input type="file" name="LetsImages" id="m.Lets.Images" /> <br />
</div>
</div>
<div class="form-group">
<div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
#Html.LabelFor(m => m.Lets.Description, new { #class="mdl-textfield__label" })
#Html.TextBoxFor(m => m.Lets.Description, new { #class= "form-control mdl-textfield__input" })
</div>
</div>
<div class="form-group">
<div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
#Html.LabelFor(m => m.Lets.Credits, new { #class="mdl-textfield__label" })
#Html.TextBoxFor(m => m.Lets.Credits, new { #class= "form-control mdl-textfield__input" })
</div>
</div>
<div class="form-group">
<div class="mdl-cell col-md-10">
#Html.LabelFor(m => m.Lets.Group)
#Html.DropDownListFor(m => m.Lets.GroupId, new SelectList(Model.Groups, "Id", "Name"), "-- Selecteer een Groep --", new { #class= "form-control" })
</div>
</div>
#Html.ActionLink("Terug naar het overzicht", "Index", new { }, new { #class= "mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" })
<input type="submit" value="Save" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" />
</fieldset>
}
Controller:
[HttpGet]
public IActionResult Create()
{
var model = new LetsViewModel
{
Lets = new Lets(),
Groups = _kletsContext.Groups.AsEnumerable(),
Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name)
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(LetsViewModel model)
{
LetsViewModel viewModel = null;
try
{
if(!ModelState.IsValid)
throw new Exception("The Lets model is not valid!");
var letsImage = "INSERT LOGIC FOR IMAGEUPLOAD HERE?";
model.Lets.UserId = User.GetUserId();
model.Lets.StatusId = 1;
model.Lets.Images = letsImage;
_kletsContext.Lets.Add(model.Lets);
if (_kletsContext.SaveChanges() == 0)
{
throw new Exception("The Lets model could not be saved!");
}
//Success(CreateMessage(ControllerActionType.Create, "klets", model.Name), true);
return RedirectToAction("Index", "Home");
}
catch(Exception ex)
{
ModelState.AddModelError(string.Empty, "Unable to save changes.");
viewModel = new LetsViewModel
{
Lets = model.Lets,
Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name)
};
}
return View(viewModel);
}
I've added the place where I think the logic should come?
So what I want to do is:
Upload the Image to a folder
Rename it
Store the relative path as a string to the db.
Thank you
There is no HttpPostedFileBase in MVC6, you have to use IFormFile like this:
public FileDetails UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent
};
}
return fileDetails;
}
You can upload images using handlers , link to tutorials are
http://www.c-sharpcorner.com/blogs/uploading-files-using-jquery-ajax-in-asp-net1
http://www.binaryintellect.net/articles/f2a2f1ee-e18a-416b-893e-883c800f83f4.aspx
http://www.dotnetjalps.com/2011/12/async-file-upload-with-jquery-and.html?m=1
These tutorials are using jquery to pass the image to the handler and then handler saving the image in the folder. You can rename the image before uploading to the folder and get back the saved image name in response and then save image name along with other model properties.
I eventually got it working by:
include using Microsoft.AspNet.Hosting; and using System.IO;
using System.Net.Http.Headers;
Add public IHostingEnvironment _environment { get; set;}
to your controller (I added it to my commoncontroller, and then it's available to me on my controller)
Then in my create:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(LetsViewModel model, IFormFile LetsImages)
{
LetsViewModel viewModel = null;
try
{
if(!ModelState.IsValid)
throw new Exception("The Lets model is not valid!");
if(LetsImages != null)
{
var targetDirectory = Path.Combine(_environment.WebRootPath, string.Format("images/uploads"));
var fileName = ContentDispositionHeaderValue
.Parse(LetsImages.ContentDisposition)
.FileName
.Trim('"');
var savePath = Path.Combine(targetDirectory, fileName);
var relPath = "/images/uploads/" + fileName;
try
{
LetsImages.SaveAs(savePath);
model.Lets.Images = relPath;
}
catch
{
throw new Exception("There was a problem with saving the file!");
}
}
else
{
model.Lets.Images = null;
}
model.Lets.UserId = User.GetUserId();
model.Lets.StatusId = 1;
_kletsContext.Lets.Add(model.Lets);
if (_kletsContext.SaveChanges() == 0)
{
throw new Exception("The Lets model could not be saved!");
}
//Success(CreateMessage(ControllerActionType.Create, "klets", model.Name), true);
return RedirectToAction("Index", "Home");
}
catch(Exception ex)
{
ModelState.AddModelError(string.Empty, "Unable to save changes.");
viewModel = new LetsViewModel
{
Lets = model.Lets,
Groups = _kletsContext.Groups.AsEnumerable(),
Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name)
};
}
return View(viewModel);
}
Just make sure you've created the folder where the images should belong, else it's not going to work without any error!
Thanks everybody for your help!

Categories

Resources