Problem with file submission through ajaxFormData

0

Good, I have a problem regarding the way you sent file values, how I use ajax in jquery and the jquery-formdata library, I get the error of TypeError: 'slice' called on an object that does not implement interface Blob. I think it's because all those values in the fields I store them as a JSON object, plus I use laravel to save the images, or at least that's supposed:

function FormInfo()
{
    var valor = $("#addUserForm").serialize();
    var json = {};

    var datos = valor.split("&");

    datos.forEach(function(element, index) {
        var info = element.split("=");
        json[""+info[0]] = info[1];
    });

    json["avatar"] = document.getElementById('plox').files[0];

    return json;
}

This is the code with which I get the values of the input and I pass them to a json as I add the value of the file.

$("#addUserForm").submit(function (event) {
    //Ocultando todos los mensajes de error
    $('.chip').hide();

    event.preventDefault();
    $.ajaxFormData({
        type: "post",
        dataType: "html",
        url: 'users/add',
        contentType: "multipart/form-data",
        data : FormInfo(),
        success: function (response) {
            $("#addUser").modal('close');
            $("#cont-users").addClass('formSubmitted');
            Materialize.toast('Registro ingresado', 3000, 'rounded');
        }

And this one here is the code by which I send the data, and this is the line of code of the user driver in laravel that gives me error:

$request->file('avatar')->store('public');

This is the form tag

<form method="POST" action="http://127.0.0.1:8000/users/add" accept-charset="UTF-8" id="addUserForm"><input name="_token" value="kl5DY0aNK0mUt3lR9pGnoeEX8GOlPhdLJkSSh0hd" type="hidden">
    
asked by Carlos Alexander Lemus Mojica 08.09.2017 в 04:05
source

1 answer

1

You can not send binary files through JSON; what you must do is create a FormData object with the form data and send this object by AJAX.

data: new FormData($('#addUserForm')[0]),

Likewise you must set processData to false:

processData: false,

From the jQuery documentation:

  

processData (default: true)

     

Type: Boolean

     

By default, data passed in to the data option as an object   (technically, anything other than a string) will be processed and   transformed into a query string, fitting to the default content-type   "application / x-www-form-urlencoded" . If you want to send to   DOMDocument, or other non-processed data, set this option to false.

By default, the object passed in data is transformed into a query string; this of course will not work with binary files since it must be sent as such. Regarding contentType you can eliminate it or set it in false to have an automatic mime.

    
answered by 08.09.2017 / 15:57
source