How to convert an image to base64 in ASP.NET MVC?

1

I have a WS that receives the following data:

    <token>string</token>
    <NroComputacion>string</NroComputacion>
    <NroCarnet>string</NroCarnet>
    <Foto>string</Foto>
    <Firma>string</Firma>
    <Emision>dateTime</Emision>
    <Vencimiento>dateTime</Vencimiento>
    <ObservacionesCarnet>string</ObservacionesCarnet>

The problem is that the photo and the signature at the time of loading are an image, which has to be converted to base64 and a string so that the call is made correctly, and I do not know how to do the conversion or how pass the data.

for now this is my Models:

     public class CarnetViewModels
{
    public class CarnetNuevo
    {
        public string Computacion { get; set; }

        public string NroCarnet { get; set; }

        public HttpPostedFileBase Foto { get; set; }

        public HttpPostedFileBase Firma { get; set; }

        [DataType(DataType.Date)]
        public DateTime Emision { get; set; }

        [DataType(DataType.Date)]
        public DateTime Vencimiento { get; set; }
        public string Observaciones { get; set; }

    }


}

This my controller

    [HttpPost]
    public ActionResult Nuevo(Models.CarnetViewModels.CarnetNuevo carnet)
    {

        var token = Session["token"] as string;
        //27662956

        SRCarnets.CarnetsSoapClient wsCarnet = new SRCarnets.CarnetsSoapClient();
        SRCarnets.RespuestaSimple outCrear = new SRCarnets.RespuestaSimple();
        outCrear =  wsCarnet.CrearCarnet(token, "27662956", carnet.NroCarnet, carnet.Foto, carnet.Firma, carnet.Emision, carnet.Vencimiento, carnet.Observaciones);
        return View();
    }

and my View:

     <form name="nuevoCarnet" accept-charset="utf-8" action="@Url.Action("Nuevo", "Carnet")" method="POST" >
    <div class="parent">
        <img src="~/img/carnet-frente.png" class="bg" />
        <table class="overlay">
            <tr>
                <td width="30%">
                    <div width="50%">
                        @Html.TextBoxFor(m => m.Foto, new { type = "file" })
                    </div>
                </td>
                <td width="70%" rowspan="2">
                    <table width="100%" class="presentacionCarnet">
                        <tr>
                            <th width="25%">Carnet N&deg;</th>
                            <td>@Html.EditorFor(m => m.NroCarnet, null)</td>
                        </tr>
                        <tr>
                            <th>Licencia N&deg;</th>
                        </tr>
                        <tr>
                            <th>Apellido</th>
                        </tr>
                        <tr>
                            <th>Nombre</th>
                        </tr>
                        <tr>
                            <th>C.I. N&deg;</th>
                        </tr>
                        <tr>
                            <th>Fecha de Nac</th>

                        </tr>
                        <tr>
                            <th>Nacionalidad</th>
                        </tr>
                        <tr>
                            <th>Municipalidad</th>
                        </tr>
                        <tr>
                            <th>Domicilio</th>
                        </tr>
                        <tr>
                            <th>Fecha de Emisión</th>
                            <td> @Html.EditorFor(m => m.Emision, null)</td>
                        </tr>
                        <tr>
                            <th>Fecha de Vencimiento</th>
                            <td> @Html.EditorFor(m => m.Vencimiento, null)</td>
                        </tr>
                        <tr>
                            <th valign="top">Observaciones</th>
                            <td>@Html.EditorFor(m => m.Observaciones, null)</td>
                        </tr>
                    </table>
            </tr>
            <tr>
                <td>
                    @Html.TextBoxFor(m => m.Firma, new { type = "file"})
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <br />
                    <input class="btn btn-primary" type="submit" value="Generar Carnet" />
                    <a href="javascript:history.go(-1);" class="btn btn-danger"><i class="glyphicon glyphicon-remove"></i> Cancelar</a>
                </td>
            </tr>
        </table>
    </div>
</form> 
    
asked by Sebastian Kullman 26.10.2016 в 20:27
source

4 answers

1

You can also work on the front-end as follows:

function leerArchivo() {
  if (this.files && this.files[0]) {
    var FR= new FileReader();
    FR.onload = function(e) {
      document.getElementById("imgNinja").value = e.target.result;
      console.log(e.target.result);
    };       
    FR.readAsDataURL( this.files[0] );
  }
}
document.getElementById("inp").addEventListener("change", leerArchivo, false);
<input id="inp" type='file'>
<input type="hidden" id="imgNinja">

And on the server, read the value of the imgNinja that is already in Base64

    
answered by 26.10.2016 / 20:48
source
1

You should get the byte [] from the HttpPostedFileBase

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

Source Convert HttpPostedFileBase to byte []

Assigning the byte [] to the convert

Convert.ToBase64String (Method) (Byte [])

you get the string encoded to base64, this is the one you send to the service

    
answered by 26.10.2016 в 20:44
0

You could add the FirmBase64 property to your class:

public class CarnetNuevo
{
    public string Computacion { get; set; }

    public string NroCarnet { get; set; }

    public HttpPostedFileBase Foto { get; set; }

    public HttpPostedFileBase Firma { get; set; }

    [DataType(DataType.Date)]
    public DateTime Emision { get; set; }

    [DataType(DataType.Date)]
    public DateTime Vencimiento { get; set; }
    public string Observaciones { get; set; }

    public string FirmaBase64 { get {
        if (Firma == null)
             return null;
        byte[] bytes = new byte[Firma.InputStream.Length];
        Firma.InputStream.Read(bytes, 0, byte.Length - 1)
        return Convert.ToBase64String(bytes);
    }
}

In this class you can check the value of the FirmBase64 property and it will return what you need. Good luck!

    
answered by 26.10.2016 в 21:18
0

I solved it thanks to the response of fredyfx

I keep the code like this:

in my View edit the input file like this:

    <div>
         <input id="imp" type='file' class="file" multiple data-show-upload="false" data-show-remove="false" data-show-caption="true"> 
          @Html.TextBoxFor(m => m.Foto, new { type = "hidden" })
   </div>

   <div>
        <input id="inp" type='file' class="file" multiple data-show-upload="false" data-show-caption="true"> 
        @Html.TextBoxFor(m => m.Firma, new { type = "hidden" })

the input that you rightly believe will leave it hidden and with this javascript function the padding

    function leerArchivofoto() {
        if (this.files && this.files[0]) {
            var FR1 = new FileReader();
            FR1.onload = function (e) {
                document.getElementById("Foto").value = e.target.result;
            };
            FR1.readAsDataURL(this.files[0]);
        }
    }
    document.getElementById("imp").addEventListener("change", leerArchivofoto, false);

    function leerArchivofirma() {
        if (this.files && this.files[0]) {
            var FR2 = new FileReader();
            FR2.onload = function (e) {
                document.getElementById("Firma").value = e.target.result;
            };
            FR2.readAsDataURL(this.files[0]);
        }
    }
    document.getElementById("inp").addEventListener("change", leerArchivofirma, false);

Change the attributes of Photo and Signature by string

    public class CarnetNuevo
    {
        public string Computacion { get; set; }
        [Required(ErrorMessage = "El campo Nº de Carnet no puede estar vacio")]
        public string NroCarnet { get; set; }
        [Required(ErrorMessage = "Se debe agregar una fotografia")]
        public string Foto { get; set; }
        [Required(ErrorMessage = " Se debe agregar una firma")]
        public string Firma { get; set; }

        [DataType(DataType.Date)]
        public DateTime Emision { get; set; }

        [DataType(DataType.Date)]
        public DateTime Vencimiento { get; set; }
        public string Observaciones { get; set; }
    }

and finally in my controller I made the call:

    public ActionResult Nuevo(Models.CarnetViewModels.CarnetNuevo carnet)
    {
        //obtengo el token
        var token = Session["token"] as string;
        //este sera el numero de computacion = 27662956
        //instancio mi WS
        SRCarnets.CarnetsSoapClient wsCarnet = new SRCarnets.CarnetsSoapClient();
        //Instancio el output
        SRCarnets.RespuestaSimple outCrear = new SRCarnets.RespuestaSimple();
        //realizo la llamada
        outCrear =  wsCarnet.CrearCarnet(token, "27662956", carnet.NroCarnet, carnet.Foto, carnet.Firma, carnet.Emision, carnet.Vencimiento, carnet.Observaciones);
        return View();
    }
    
answered by 26.10.2016 в 22:52