ItShine ItShine - 2 months ago 11
C# Question

Send a base64 image to controller razor ASP.Net MVC4

I want to send a base64 image from my view to controller
Here is my view code

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<img width="60" height="60" alt="" src="data:image/jpeg;base64,....."/>

@Html.TextArea("resultText")
<input type="submit" style="margin-left:40px;cursor:pointer;" id="l" value="Envoyer"/>
}


And in my controller I want to get the image in argument
Here is the code of the controller

public ActionResult Index(HttpPostedFileBase imageFile)
{
//Conversion
if (imageFile!= null && imageFile.ContentLength > 0)
{

// for now just fail hard if there's any error however in a propper app I would expect a full demo.

using (var engine = new TesseractEngine(Server.MapPath(@"./tessdata"), "eng", EngineMode.Default))
{
// have to load Pix via a bitmap since Pix doesn't support loading a stream.
using (var image = new System.Drawing.Bitmap(imageFile.InputStream))
{
using (var pix = PixConverter.ToPix(image))
{
using (var page = engine.Process(pix))
{
//meanConfidenceLabel.InnerText = String.Format("{0:P}", page.GetMeanConfidence());
//ViewBag.meanConfidenceLabel = String.Format("{0:P}", page.GetMeanConfidence());
ViewBag.resultText = page.GetText();

}
}
}
}

}

return View();
}


The method above accepts an uploded image in argument but I want to have an base64 image instead.
I've tried to get it as a string by passing the value of the src but It didn't work .

Answer Source

I would treat this the same as trying to post any other string value to a controller action. First, you need to put the image data into a form field so it will be posted with the form:

<input type="hidden" name="imageData" value="data:image/jpeg;base64,....."/>

Then you need to update your action signature to capture the new field:

public ActionResult Index(string imageData)
{
  ...
}