防止 AJAX 以字符串形式发送文件

2023-12-24

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

我想使用发送它FormData and AJAX。仅供参考:我正在使用 Vue 和 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
            },
        });

但是当我尝试在控制器中获取文件时,我得到了[object File]。所以,我愿意gettype($imagesFile)结果是string。这显然是一个意想不到的结果。我想将文件存储在服务器中。我怎样才能做到这一点?

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

    return response()->json([
            'success' => true,
            'message' => $imagesFile,
        ]);
}

this.form.imagesFile是一个数组,您必须将 File 传递给 FormData 对象。另外,不要设置内容类型。

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

您可以通过以下方式访问该文件$request->file('imagesFile');

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

防止 AJAX 以字符串形式发送文件 的相关文章