使用jquery文件上传插件和自定义ajax构建照片上传器


building a photo uploader using the jquery-file-upload plugin and custom ajax

我正在构建一个照片上传表单,并决定使用jQuery插件jquery-file-upload,但遇到了一些问题。。。和问题。

首先,我使用的代码(使用basic版本):

// File upload function
jQuery(function() {
    jQuery('#pick-photos').click(function(){
        jQuery('#file-upload').click();
    });
    // Initialize the jQuery File Upload plugin
    jQuery('#photo-upload').fileupload({
        dataType: 'json',
        add: function (e, data) {
            jQuery.each(data.result.files, function (index, file) {
            jQuery('<p/>').text(file.name).appendTo(document.body);
        });
            // Append the file name and file size
            tpl.find('p').text(data.files[0].name)
                         .append('<i>' + formatFileSize(data.files[0].size) + '</i>');
            jQuery('#upload').click(function() {
                data.submit();
            });         
        },
        progressall: function(e, data) {
            // Calculated the completion percentage of the upload
            var progress = parseInt(data.loaded / data.total * 100, 10);
            jQuery('#upload-progress .progress-bar').css(
                'width',
                progress + '%'
           );
        },
    });
    // Helper function that formats the file sizes
    function formatFileSize(bytes) {
        if (typeof bytes !== 'number') {
            return '';
        }
        if (bytes >= 1000000000) {
            return (bytes / 1000000000).toFixed(2) + ' GB';
        }
        if (bytes >= 1000000) {
        return (bytes / 1000000).toFixed(2) + ' MB';
        }
        return (bytes / 1000).toFixed(2) + ' KB';
    }
});

我面临的问题是这行代码jQuery('#photo-upload').fileupload({ 上的错误Uncaught TypeError: Object [object Object] has no method 'fileupload'

其次,我想知道如何在这段代码中包含自定义ajax。。。以便我可以根据成功或错误更改页面内容。

任何帮助都会被完全接受!

为了在成功或错误(或两者都有)时执行一些代码,jquery文件上传提供了一些回调:

  • 完成(相当于成功)
  • 失败(相当于错误)
  • 始终(相当于完整)

这些回调中的每一个都具有与add回调相同的参数。

基本版本的wiki给出了一个例子:

$(function () {
    $('#fileupload').fileupload({
        dataType: 'json',
        add: function (e, data) {
            data.context = $('<p/>').text('Uploading...').appendTo(document.body);
            data.submit();
        },
        done: function (e, data) {
            data.context.text('Upload finished.');
        }
    });
});

对于您的问题,您是否包括这些文件?

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/vendor/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>