Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
Prevent AJAX for sending file as string

I have a file stored in this.form.imagesFile variable. It contains file below: enter image description here

And I want to send it using FormData and AJAX. FYI: I am using Vue and Laravel.

let getImg = [];
        this.form.variantsProd.forEach((item) => {
            let totalImagesFile = $('.images' + item.id)[0].files.length; //Total Images
            let imagesFile = $('.images' + item.id)[0];
            for (let i = 0; i < totalImagesFile; i++) {
                getImg.push(imagesFile.files[i]);
            }
            this.form.imagesFile = getImg;
        });
        this.form.totalImagesFile = getImg.length;

        let formData = new FormData();
        formData.append('imagesFile', this.form.imagesFile);

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            },
        });
        const token = localStorage.getItem('token-staff');
        var self = this;
        $.ajax({
            url: `${BASE_URL}/api/staff/products/store`,
            method: 'post',
            data: formData,
            enctype: 'multipart/form-data',
            cache: false,
            contentType: false,
            processData: false,
            dataType: 'JSON',
            async: true,
            headers: {
                'Content-Type': undefined,
            },
            xhr: function () {
                let myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', `Bearer ${token}`);
            },
            error: function (response) {
                console.log(response);
            },
            success: function (result) {
                if (result.errors) {
                    console.log(result);
                } else {
                    //
                } //endif
            },
        });

But when I try to get the file in controller, I get [object File]. So, I do gettype($imagesFile) and the result is string. This is obviously unexpected result. I want store the file in server. How can I do that?

public function store(Request $request)
{
    $imagesFile = $this->request->get('imagesFile');

    return response()->json([
            'success' => true,
            'message' => $imagesFile,
        ]);
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

this.form.imagesFile is an array you have to pass a File to the FormData object. Also, do not set the content type.

    let formData = new FormData(); 
    this.form.variantsProd.forEach((item) => {
        let totalImagesFile = $('.images' + item.id)[0].files.length; //Total Images
        let imagesFile = $('.images' + item.id)[0];
        for (let i = 0; i < totalImagesFile; i++) {
            getImg.push(imagesFile.files[i]);
            formData.append('imagesFile', imagesFile.files[i]);
        }
        this.form.imagesFile = getImg;
    }); 
    ...
    $.ajax({
        url: `${BASE_URL}/api/staff/products/store`,
        method: 'post',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'JSON',
        async: true,
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', `Bearer ${token}`);
        },
        error: function (response) {
            console.log(response);
        },
        success: function (result) {
            if (result.errors) {
                console.log(result);
            } else {
                //
            } //endif
        },
    });        

You can access the file via $request->file('imagesFile');

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda