防止 AJAX 将文件作为字符串发送 [英] Prevent AJAX for sending file as string

查看:25
本文介绍了防止 AJAX 将文件作为字符串发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件存储在 this.form.imagesFile 变量中.它包含以下文件:

I have a file stored in this.form.imagesFile variable. It contains file below:

我想使用 FormDataAJAX 发送它.仅供参考:我正在使用 Vue 和 Laravel.

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

但是当我尝试在控制器中获取文件时,我得到 [object File].所以,我做了gettype($imagesFile),结果是string.这显然是意料之外的结果.我想将文件存储在服务器中.我该怎么做?

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

推荐答案

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

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

您可以通过 $request->file('imagesFile');

这篇关于防止 AJAX 将文件作为字符串发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆