duanlin1931 2014-12-03 18:25
浏览 60
已采纳

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

I'm trying to upload files through Ajax call and 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.

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? 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

  • 写回答

1条回答 默认 最新

  • dtt3399 2014-12-04 04:50
    关注

    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,
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog