How do I pass an image from my view to a controller? MVC

1

Hi, I have the following problem, I need to get an image of an input and pass it to the controller; The code I use is the following: HTML:

<div class="row">
    <div class="col-xs-12 col-sm-10 offset-sm-1">
        <input name="Portada" type="file" id="filePicker" />
    </div>
</div>
<button class="btn btn-primary btn-block" type="button" onclick="Modificar()">Guardar cambios</button>

JS:

function Modificar() {
      var Portada = $('#filePicker').prop("files")[0];
        var url = "@Url.Action("Modificar", "Dispositivos")";
        var data = { Portada: Portada };
        $.post(url, data).done(function (data) {
            if (data) {
            }
        });
    }

Controller:

 public ActionResult Modificar(HttpPostedFileBase Portada)
    {--- codigoControlador}

With this code it gives an error in js and does not reach the controller, if the input is null if it enters the controller. I hope you can help me.

    
asked by Assembler code 19.04.2018 в 05:34
source

1 answer

3

To send a file to the controller what you would have to do on the client side is this:

function Modificar() {
 var fichero = document.getElementById("filePicker").files[0];
 var datosFormulario = new FormData();
 datosFormulario.append("imagen", fichero);
 datosFormulario.append("Id", 2);
 $.ajax({
    url: 'http://ejemplo.com/accionControlador/',
    data: datosFormulario,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data){
      alert(data);
 }

});     }

On the controller

public ActionResult Modificar(int Id){
    if (Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
        }
}

}

The advantage you have when using FormData is that you can send all the files you want and also the data you need. In the example you can see that I have added the value of Id.

Greetings.

    
answered by 19.04.2018 / 09:55
source