0

I'm using blueimp/jQuery-File-Upload's plugin to upload files and I'm trying (unsuccessfully) to add a data-attribute to the preview when the upload is done.

Here is the code:

$('#fileupload').fileupload({
    autoUpload: true,
    disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
    maxFileSize: 5000000,

    acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp|doc?x|pdf|xml|psd|tif)$/i,

    uploadTemplateId: null,
    downloadTemplateId: null,
    uploadTemplate: function (o) {
        var rows = $();
        $.each(o.files, function (index, file) {
            var row = $('<div class="template-upload fade">' +
                '<span class="preview"></span>' +
                '<p class="name"></p>' +
                '<div class="error"></div>' +
                '<div class="progress"></div>' +
                (!index && !o.options.autoUpload ?
                    '<button class="start" disabled>Start</button>' : '') +
                (!index ? '<button class="cancel">Cancel</button>' : '') +
                '</td>' +
                '</div>');
            row.find('.name').text(file.name);
            row.find('.size').text(o.formatFileSize(file.size));
            if (file.error) {
                row.find('.error').text(file.error);
            }
            rows = rows.add(row);
        });
        return rows;
    },
    downloadTemplate: function (o) {
        var rows = $();
        $.each(o.files, function (index, file) {
            var row = $('<div class="template-download fade">' +
                '<span class="preview"></span>' +
                '<p class="name"></p>' +
                (file.error ? '<div class="error"></div>' : '') +
                //'<button class="delete">Delete</button>' +
                '</div>');
            row.find('.size').text(o.formatFileSize(file.size));
            if (file.error) {
                row.find('.name').text(file.name);
                row.find('.error').text(file.error);
            } else {
                row.find('.name').append($('<a></a>').text(file.name));
                if (file.thumbnailUrl) {
                    row.find('.preview').append(
                        $('<a></a>').append(
                            $('<img>').prop('src', file.thumbnailUrl)
                        )
                    );
                }
                row.find('a')
                    .attr('data-gallery', '')
                    .prop('href', file.url);
                row.find('button.delete')
                    .attr('data-type', file.delete_type)
                    .attr('data-url', file.delete_url);
            }
            rows = rows.add(row);
        });
        return rows;
    }

    // Uncomment the following to send cross-domain cookies:
    //xhrFields: {withCredentials: true},
}).bind('fileuploaddone', function(e, data) {

    var arquivo = data.result.files[0].url;
    var varCodTipoProcesso = $('.indexador-campo').data('cod-tipo-processo');
    var varCodEstabelecimento = $('.estabelecimento-select').parent().children('a').children('span').data('cod-estabelecimento');
    var varArrayCampos = [];
    var tipos = ['jpg', 'png', 'gif', 'psd', 'bmp', 'tif', 'pdf', 'xml'];
    var nome = data.result.files[0].name;

    var today = new Date();
    var s = today.getSeconds();
    var i = today.getMinutes();
    var h = today.getHours();
    var dd = today.getDate();
    var mm = today.getMonth();
    var yyyy = today.getFullYear();

    now = '' + yyyy + mm + dd + h + i + s;

    var filename = now + '.' + nome.substr(nome.lastIndexOf('.')+1);

    $('.indexadores-campos .row input').each(function() {
        var indexadoresData = {};
        indexadoresData.nomCampo = $(this).attr('name');
        indexadoresData.numOrdem = $(this).data('num-ordem');
        indexadoresData.valor = $(this).val();
        varArrayCampos.push(indexadoresData);
    });

    console.log(varCodTipoProcesso)

    $.getJSON('/sistema/ajax/setUploadFileJson.php', {
        arquivo:  arquivo,
        varCodProcesso: null,
        varCodTipoProcesso: varCodTipoProcesso,
        varCodEstabelecimento: varCodEstabelecimento,
        varCodTipoDocumento: null,
        varArrayCampos: varArrayCampos,
        pasta: null,
        tipos: tipos,
        nome: filename
    }).done(function(doc) {
        console.log(data.codDocumento); //there's the data I want to add to the preview
    }).fail(function() {
        console.log('error');
    });

});

// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
    'option',
    'redirect',
    window.location.href.replace(
        /\/[^\/]*$/,
        '/cors/result.html?%s'
    )
);

// Upload server status check for browsers with CORS support:
if ($.support.cors) {
    $.ajax({
        type: 'HEAD'
    }).fail(function () {
        $('<div class="alert alert-danger"/>').text('Upload server currently unavailable - ' + new Date()).appendTo('#fileupload');
    });
}

// Load & display existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
    // Uncomment the following to send cross-domain cookies:
    //xhrFields: {withCredentials: true},
    url: $('#fileupload').fileupload('option', 'url'),
    dataType: 'json',
    context: $('#fileupload')[0]
}).always(function () {
    $(this).removeClass('fileupload-processing');
}).done(function (result) {
    $(this).fileupload('option', 'done')
        .call(this, $.Event('done'), {result: result});
});

I managed to get the data from the server, but douldn't add it to the preview and I can't figure out how to do it. Can anybody help me on this?

1 Answer 1

1

The answered is already available and both will work fine.

You need to use additional plugin jquery.fileupload-ui.js as mentioned in answer (https://stackoverflow.com/a/11016888/2871356) or as mentioned in answer(https://stackoverflow.com/a/18284685/2871356) Place this inside your add(e, data) callback function, adjusting for your own html elements accordingly:

$('body').append('<img src="' + URL.createObjectURL(data.files[0]) + '"/>');
Sign up to request clarification or add additional context in comments.

Comments

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.