Jquery 文件上传上传完成后添加数据进行预览

Jquery File Upload Add data to preview when upload is done

我正在使用 blueimp/jQuery-File-Upload 的插件上传文件,我正在尝试(未成功)在上传完成后向预览添加数据属性。

代码如下:

$('#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});
});

我设法从服务器获取数据,但没有将其添加到预览中,我不知道该怎么做。有人可以帮我解决这个问题吗?

答案已经可用,两者都可以正常工作。

您需要使用额外的插件 jquery.fileupload-ui.js 如答案中所述 () or as mentioned in answer() 将其放入您的 add(e , data) 回调函数,相应地调整你自己的 html 个元素:

$('body').append('<img src="' + URL.createObjectURL(data.files[0]) + '"/>');