1

Perhaps this question has been asked before several times but I didn't found any answer that helps me. I know also the existence of OneUpUploaderBundle but I think my situation will not work with this plugin (if any knows how to do it, let me know).

I need to upload several files but also I'll have dynamic file inputs as you'll see on the code below. So the only idea I get to do this is onchange event from the select build dynamic file fields. This is what I've right now and it works:

$(document).ready(function () {
    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"),
            baseFilUploadHTML = '<span class="btn btn-success fileinput-button">' +
                '<i class="glyphicon glyphicon-plus"></i>' +
                '<span>Agregar archivos ...</span>' +
                '<input id="fileUpload' + selectedData.id + '" type="file" name="fileUpload' + selectedData.id + '" multiple></span>' +
                '<br><br>' +
                '<div id="progress' + selectedData.id + '" class="progress">' +
                '<div class="progress-bar progress-bar-success"></div>' +
                '</div>' +
                '<div id="fileUpload' + selectedData.id + '" class="files"></div>' +
                '<br>',
            uploadButton = $('<button/>').addClass('btn btn-primary').prop('disabled', true).text('Procesando...').on('click', function () {
                var $this = $(this),
                    data = $this.data();
                $this.off('click').text('Abort').on('click', function () {
                    $this.remove();
                    data.abort();
                });
                data.submit().always(function () {
                    $this.remove();
                });
            });

        selectedIdsTipoRecaudo.push(id);

        if (id == 1) {
            // Rif
        } else if (id == 2) {
            // Registro Mercantil
        } else {
            $('#uploadArea').append(baseFilUploadHTML);
        }

        $('#fileUpload' + selectedData.id).fileupload({
            url: url,
            dataType: 'json',
            autoUpload: false,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            maxFileSize: 2000000, // 2 MB
            disableImageResize: /Android(?!.*Chrome)|Opera/
                .test(window.navigator.userAgent),
            previewMaxWidth: 100,
            previewMaxHeight: 100,
            previewCrop: true
        }).on('fileuploadadd', function (e, data) {
            data.context = $('<div/>').appendTo('#fileUpload' + selectedData.id);
            $.each(data.files, function (index, file) {
                var node = $('<p/>').append($('<span/>').text(file.name));
                if (!index) {
                    node.append('<br>').append(uploadButton.clone(true).data(data));
                }
                node.appendTo(data.context);
            });
        }).on('fileuploadprocessalways', function (e, data) {
            var index = data.index,
                file = data.files[index],
                node = $(data.context.children()[index]);
            if (file.preview) {
                node.prepend('<br>').prepend(file.preview);
            }
            if (file.error) {
                node.append('<br>').append($('<span class="text-danger"/>').text(file.error));
            }
            if (index + 1 === data.files.length) {
                data.context.find('button').text('Subir').prop('disabled', !!data.files.error);
            }
        }).on('fileuploadprogressall', function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress' + selectedData.id + ' .progress-bar').css(
                'width',
                progress + '%'
            );
        }).on('fileuploaddone', function (e, data) {
            $.each(data.result.files, function (index, file) {
                if (file.url) {
                    var link = $('<a>').attr('target', '_blank').prop('href', file.url);
                    $(data.context.children()[index]).wrap(link);
                } else if (file.error) {
                    var error = $('<span class="text-danger"/>').text(file.error);
                    $(data.context.children()[index]).append('<br>').append(error);
                }
            });
        }).on('fileuploadfail', function (e, data) {
            $.each(data.files, function (index) {
                var error = $('<span class="text-danger"/>').text('Falló la carga de archivos.');
                $(data.context.children()[index]).append('<br>').append(error);
            });
        }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
    });
});

I believe that jQuery-FileUpload handled files upload through Ajax, I'm right? In that case how do I handle files on the Symfony2 controller since for example I need to persist their names and full path to a table column? How you handle this? Any example taking my code as use case?

I've read this, this and this but is not so helpful as I though. Also official docs for Handle file uploads with Doctrine but not clue so far.

1
  • Use uploadify jq plugin.I also use this for uploading multiple images in my project. uploadify.com/documentation Commented Nov 28, 2014 at 5:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.