简体   繁体   English

文件不是通过Ajax请求发送的,在请求中不是“文件名”,而在服务器端是空请求

[英]Files are not send through Ajax request, get not “filenames”in the request and gets empty request on the server side

I'm trying to upload files through Ajax call and jQuery. 我正在尝试通过Ajax调用和jQuery上传文件。 Each input[type="file"] is handled dynamically as you will see on the code below and are created on the change event for the Select2 element. 您将在下面的代码中看到动态处理的每个input[type="file"]并在Select2元素的change事件上创建它们。

var tipoRecaudo = $('#tipoRecaudo'),
    tipo_recaudo = tipoRecaudo.val(),
    selectedIdsTipoRecaudo = [];

tipoRecaudo.select2({
    ajax: {
        dataType: 'json',
        url: function () {
            return Routing.generate('obtenerRecaudosTramite');
        },
        data: function (tipo_recaudo) {
            return {
                filtro: tipo_recaudo
            }
        },
        results: function (data) {
            var myResults = [];
            $.each(data.entities, function (index, item) {
                if (selectedIdsTipoRecaudo.indexOf(item.id.toString()) === -1) {
                    myResults.push({
                        'id': item.id,
                        'text': item.nombre
                    });
                }
            });
            return {
                results: myResults
            };
        }
    },
    formatAjaxError: function () {
        return Translator.trans('mensajes.msgNoConexionServidor', {}, 'AppBundle');
    }
}).change(function () {
    var id = $(this).val(),
        selectedData = tipoRecaudo.select2("data"),
        htmlTpl = '<table class="table"><caption>'+ selectedData.text + '</caption><tbody><tr><td>';
        htmlTpl += '<input type="hidden" name="tipoRecaudos[]" id="tipoRecaudo ' + id + '" value="' + selectedData.id + '" /><div class="row"><div class="col-xs-6"><div class="form-group"><input type="file" id="recaudosNombreArchivo' + id + '" name="recaudos[nombre_archivo][]" multiple="multiple" class="form-control" /></div></div></div></div>';
        htmlTpl += '</td></tr></tbody></table>';

    selectedIdsTipoRecaudo.push(id);
    $('#recaudoContainer').append(htmlTpl);
});

$('#recaudoContainer').on('change', 'input[type=file]', function (event) {
    $("input:file").filestyle({
        buttonText: "Seleccionar archivo",
        iconName: "fa fa-upload",
        buttonName: "btn-primary"
    });
});

$('#btnGuardarPasoSieteAgregarProducto').on("click", function (event) {
    event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

    // Create a formdata object and add the files
    var formData = $('#formRecaudosTramites').serialize();

    $.each($('#formRecaudosTramites')[0].files, function (key, value) {
        formData = formData + '&recaudos[]=' + value;
    });

    $.ajax({
        url: Routing.generate('rpniSubirRecaudos'),
        type: 'POST',
        data: formData,
        cache: false,
        dataType: 'json',
        contentType: 'multipart/form-data',
        processData: false, // Don't process the files
        //contentType: false // Set content type to false as jQuery will tell the server its a query string request
    }).done(function (data, textStatus, jqXHR) {
        if (typeof data.error === 'undefined') {
            console.log('SUCCESS: ' + data.success);
        } else {
            // do something with error
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        // do something with fail callback
        // STOP LOADING SPINNER
    });
});

What is happening is: no filenames exists on query string, no files are upload or send through the Ajax call, instead it's sending a [object Object] , what I'm doing wrong? 发生的事情是:查询字符串上没有filenames ,没有文件通过Ajax调用上传或发送,而是发送了一个[object Object] ,我在做什么错呢? Can any give me some working code for this stuff? 可以给我一些适用的代码吗?

EDIT : 编辑

After reads the post referenced by user I change my code as the one before and now the error turns on: 读取用户引用的帖子后 ,我将代码更改为以前的代码,现在错误打开了:

TypeError: a is undefined
    ...rCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e...

What is wrong there? 那里怎么了

Note : Yes, I know there are tons of plugins for handle this like jQuery File Upload from Blueimp, Dropzone and some others but I leave them out since I start using jQuery File Uploader from inside OneupUploaderBundle on my Symfony2 project and spent 4 days without success so I move to the other side: made things by myself so I can learn something else and improve my knowledge 注意 :是的,我知道有很多用于处理此问题的插件,例如来自Blueimp,Dropzone的jQuery文件上载以及其他一些插件,但由于我从Symfony2项目的OneupUploaderBundle内部开始使用jQuery File Uploader并花了4天没有成功,所以我将它们遗漏了。所以我走到另一边:自己做东西,这样我就可以学到其他东西并提​​高知识

i think this will help you, 我认为这会帮助您,

 var fd = new FormData();
 //name is the key on the page of php to access the file
 fd.append('name', $('#aob_file')[0].files[0]);

 pass this fd object to your data field in ajax,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM