Send an image with Ajax and Jquery in MVC c #

1

I am working in MVC and I want to send an image through Ajax with Jquery, I have been able to send text data but until now I do not know how to send the image, because when I put it to see what data it sent me it comes out as null

This is the code of my form I have an input file and an input text

    <input type="text" id="texto" />
    <input type="file" id="fot" />
    <input type="button" value="enviar" onclick="uploadAjax()" />

This is a function that is called from the previous button, where my ajax is located in the jalo data with the getelementbyid and I send them in a data

'

    <script>
        function uploadAjax() {
            var inputFileImage = document.getElementById("fot").value;
            var texto = document.getElementById("texto").value;
            alert(texto + inputFileImage);
            $.ajax({

                url: 'xd/',
                type: "POST",
                data: { texto: texto, imagen: inputFileImage }
            });
        }
    </script>'

The method of the url is this because it is mvc in c # I use an actionresult in the I have two parameters that are those that are received in the data, only the text variable comes to me with a value and the HttpPostedFileBase comes out as null. In this case I just want to make sure that the data is sent because I'm going to apply it in another bigger project, but I need the how to send that image.

  public ActionResult xd(string texto, HttpPostedFileBase imagen)
    {

        string sum =  "holoa";

        return View();
    }
    
asked by NecroAny 16.04.2018 в 04:08
source

2 answers

1

To send files by AJAX to the server you must place the options contentType and processData in false and instead of sending an object in the option data you must arm an object type FormData (XHR2).

I leave the reference link: link

    
answered by 16.04.2018 в 04:29
0

Maybe you should evaluate

Send Images through ajax

do something like

<script>
    function uploadAjax() 
    {
        var inputFileImage = $("#fot")[0];
        var texto = $("#texto").val();

        var formdata = new FormData(); 
        formdata.append("image", inputFileImage);
        formdata.append("texto", texto);

        $.ajax({
            url: 'xd/',
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success:function(){
                //aqui codigo
            }
        });
    }
</script>

as selector uses jquery

    
answered by 16.04.2018 в 05:13