Skip to content Skip to sidebar Skip to footer

Prevent AJAX For Sending File As String

I have a file stored in this.form.imagesFile variable. It contains file below: And I want to send it using FormData and AJAX. FYI: I am using Vue and Laravel. let getImg = [];

Solution 1:

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


Post a Comment for "Prevent AJAX For Sending File As String"