JQuery AJAX sending files array from form

≯℡__Kan透↙ 提交于 2019-12-02 03:40:35

The problem is not your logic, the problem is that files cannot be uploaded via ajax.

But maybe you will ask, how did others do? Well, try a form plugin (another .js that works with jQuery)

I found this for you, it works using 'submit' method but maybe you can do a submit when input change or find other kind of solution with javascript actions.

Check this: http://www.miguelmanchego.com/2009/subir-archivos-usando-ajax-jquery/

Website is in Spanish but translate it to English if you need. Also that link includes a live example and source-code download.

Regards.

Son Dang

Below is my ajax settings which can upload files

method: "POST",
        url: url,
        headers: { 'Content-Type': undefined },
        transformRequest: function (data, headersGetter) {
            var formData = new FormData();
            angular.forEach(data, function (value, key) {
                if (Array.isArray(value)) {
                    // To save array of items
                    angular.forEach(value, function (value1, key1) {
                        if (value1.constructor.name != "File") {
                            angular.forEach(value1, function (value2, key2) {
                                formData.append(key + '[' + key1 + '].' + key2, value2);
                            });
                        }
                    });
                } else {
                    formData.append(key, value);
                }
            });

            return formData;
        },
        enctype: 'multipart/form-data',
        dataType: 'json',
        traditional: true,
        data: data,
        cache: false,
        processData: false,
        contentType: false
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!