Home > front end >  Prevent AJAX for sending file as string
Prevent AJAX for sending file as string

Time:09-27

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,
        ]);
}

CodePudding user response:

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');

  • Related