EDIT (Oct 2019):

6 years later and jQuery File Upload is clearly still driving folks insane. If you're finding little solace in the answers here, try a search of NPM for a modern alternative. It's not worth the hassle, I promise.

I recommended Uploadify in the previous edit but, as a commenter pointed out, they no longer appear to offer a free version. Uploadify was so 2013 anyway.


编辑:

This still seems to be getting traffic so I'll explain what I ended up doing. I eventually got the plugin working by following the tutorial in the accepted answer. However, jQuery File Upload is a real hassle and if you're looking for a simpler file upload plugin, I would highly recommend [Uploadify](http://www.uploadify.com). As an answer pointed out, it is only free for non-commercial use.

Background

我正在try 使用Bluimp的jQuery File Upload来允许用户上传文件.Out of the box it works perfectly,按照设置说明进行操作.但要在我的网站上实际使用它,我希望能够做几件事:

  • 在我现有的任何页面上包括上传程序
  • Change the directory for uploaded files

插件的所有文件都位于根目录下的文件夹中.

I've tried...

  • 将演示页面移到根目录并更新必要脚本的路径
  • Changing the 'upload_dir' and 'upload_url' options in the UploadHandler.php file as suggested here.
  • Changing the URL in the second line of the demo javascript

In all cases, the preview shows, and the progress bar runs, but the files fail to upload, and I get this error in the console: Uncaught TypeError: Cannot read property 'files' of undefined. I don't understand how all the parts of the plugin work which is making it difficult to debug.

Code

演示页面中的javascript:

$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = 'file_upload/server/php/UploadHandler.php',
    uploadButton = $('<button/>')
        .addClass('btn')
        .prop('disabled', true)
        .text('Processing...')
        .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();
            });
        });
$('#fileupload').fileupload({
    url: url,
    dataType: 'json',
    autoUpload: false,
    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
    maxFileSize: 5000000, // 5 MB
    // Enable image resizing, except for Android and Opera,
    // which actually support image resizing, but fail to
    // send Blob objects via XHR requests:
    disableImageResize: /Android(?!.*Chrome)|Opera/
        .test(window.navigator.userAgent),
    previewMaxWidth: 100,
    previewMaxHeight: 100,
    previewCrop: true
}).on('fileuploadadd', function (e, data) {
    data.context = $('<div/>').appendTo('#files');
    $.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(file.error);
    }
    if (index + 1 === data.files.length) {
        data.context.find('button')
            .text('Upload')
            .prop('disabled', !!data.files.error);
    }
}).on('fileuploadprogressall', function (e, data) {
    var progress = parseInt(data.loaded / data.total * 100, 10);
    $('#progress .bar').css(
        'width',
        progress + '%'
    );
}).on('fileuploaddone', function (e, data) {
    $.each(data.result.files, function (index, file) {
        var link = $('<a>')
            .attr('target', '_blank')
            .prop('href', file.url);
        $(data.context.children()[index])
            .wrap(link);
    });
}).on('fileuploadfail', function (e, data) {
    $.each(data.result.files, function (index, file) {
        var error = $('<span/>').text(file.error);
        $(data.context.children()[index])
            .append('<br>')
            .append(error);
    });
}).prop('disabled', !$.support.fileInput)
    .parent().addClass($.support.fileInput ? undefined : 'disabled');
});

I'm surprised by the lack of documentation; it seems like it should be a simple thing to change. I would appreciate if someone could explain how to do this.

推荐答案

几天前,我一直在寻找类似的功能,偶然发现了一个关于tutorialzine的很好的教程.下面是一个有效的示例.完整的教程可以找到here.

保存文件上传对话框的简单表单:

<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
  <input type="file" name="uploadctl" multiple />
  <ul id="fileList">
    <!-- The file list will be shown here -->
  </ul>
</form>

以下是上传文件的jQuery代码:

$('#upload').fileupload({

  // This function is called when a file is added to the queue
  add: function (e, data) {
    //This area will contain file list and progress information.
    var tpl = $('<li class="working">'+
                '<input type="text" value="0" data-width="48" data-height="48" data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" />'+
                '<p></p><span></span></li>' );

    // Append the file name and file size
    tpl.find('p').text(data.files[0].name)
                 .append('<i>' + formatFileSize(data.files[0].size) + '</i>');

    // Add the HTML to the UL element
    data.context = tpl.appendTo(ul);

    // Initialize the knob plugin. This part can be ignored, if you are showing progress in some other way.
    tpl.find('input').knob();

    // Listen for clicks on the cancel icon
    tpl.find('span').click(function(){
      if(tpl.hasClass('working')){
              jqXHR.abort();
      }
      tpl.fadeOut(function(){
              tpl.remove();
      });
    });

    // Automatically upload the file once it is added to the queue
    var jqXHR = data.submit();
  },
  progress: function(e, data){

        // Calculate the completion percentage of the upload
        var progress = parseInt(data.loaded / data.total * 100, 10);

        // Update the hidden input field and trigger a change
        // so that the jQuery knob plugin knows to update the dial
        data.context.find('input').val(progress).change();

        if(progress == 100){
            data.context.removeClass('working');
        }
    }
});
//Helper function for calculation of progress
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';
}

下面是处理数据的PHP代码示例:

if($_POST) {
    $allowed = array('jpg', 'jpeg');

    if(isset($_FILES['uploadctl']) && $_FILES['uploadctl']['error'] == 0){

        $extension = pathinfo($_FILES['uploadctl']['name'], PATHINFO_EXTENSION);

        if(!in_array(strtolower($extension), $allowed)){
            echo '{"status":"error"}';
            exit;
        }

        if(move_uploaded_file($_FILES['uploadctl']['tmp_name'], "/yourpath/." . $extension)){
            echo '{"status":"success"}';
            exit;
        }
        echo '{"status":"error"}';
    }
    exit();
}

上面的代码可以添加到任何现有表单.此程序会在添加图像后自动上载图像.此功能可以更改,您可以在提交现有表单的同时提交图像.

用实际代码更新了我的答案.所有学分都归功于代码的原始作者.

Source: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/

Jquery相关问答推荐

jQuery .first() 方法返回第一个元素的集合

在 Bootstrap 3 中向工具提示添加换行符

jquery 淡入淡出元素不显示样式为可见性:隐藏的元素

如何判断输入日期是否等于今天的日期?

使用 jQuery click 处理锚点 onClick()

Jquery .on('scroll')在滚动时不触发事件

组合数组时无法读取未定义的属性推送

使用 jQuery DataTables 时禁用最后一列的排序

将返回的 JSON 对象属性转换为(较低的第一个)camelCase

为什么 Chrome 会忽略本地 jQuery cookie?

删除索引后的所有项目

在完成前一个请求之前中止新的 AJAX 请求

通过 AJAX 和 jQuery 使用 HTML5 文件上传

使用 jQuery 将宽度设置为百分比

使用 Jquery 更改页面标题

jQuery 如果 div 包含此文本,则替换该部分文本

与 C# HashSet 等效的 JavaScript 是什么?

带有回调ajax json的jQuery自动完成

检测页面是否已完成加载

detach()、hide() 和 remove() 之间的区别 - jQuery