最近的项目里用到了Fine Uploader,最新版本是3.0。(原先叫做valums file uploader)。它的官网是:https://github.com/valums/file-uploader,下载在:https://github.com/valums/file-uploader/wiki/Releases。详细文档在GitHub:https://github.com/valums/file-uploader。

我们的一个需求是不能选择完文件后立即上传,而要手动去触发,并且,在上传完毕后,我要得到一个消息,以便下一步处理。但在官网的例子里没有这样的demo。所以我自己开荒了一下。JQuery版本的fine uploader我没开荒成功,所以下面的例子都是用“No-Dependency Fine Uploader”做的。

思路是这样的:在用户触发上传操作的时候,获取所有待上传的文件总数,每次文件上传后都会有一个onComplete事件,这时让计数器自增,直到计数器==上传文件的总数。

具体是这样做的:首先,你要定义两个全局变量,一个是对FineUploader实例的引用(updForQuestion),另一个是记录全部文件总数的变量(totalQuestionAttachmentsCount)。然后,在你创建FineUploader实例的代码里,给updForQuestion赋值,设置为当前的实例。并且,设置一个计数器变量(uploadedQuestionAttachmentsCount),在onComplete事件中让uploadedQuestionAttachmentsCount++。totalQuestionAttachmentsCount则要在用户触发上传的时候赋值,访问updForQuestion._storedFileIds.length可以得到文件总数,这个官方文档里木有,我是用Firefox Console的智能提示撸出来的。。。

全部代码如下,大家自己看一下,写的不好的地方请鄙视:

var updForQuestion = null;
var totalQuestionAttachmentsCount = 0;

function createUploader() {
    var uploadedQuestionAttachmentsCount = 0;
    var uploaderForQuestion = new qq.FineUploader({
        element: document.getElementById('file-uploader-for-question'),
        autoUpload: false,
        request: {
            endpoint: '/YourServerSideMethod'
        },
        callbacks:
        {
            onComplete: function (id, fileName, responseJSON) {
                uploadedQuestionAttachmentsCount++;
                console.log("uploadedQuestionAttachmentsCount: " + uploadedQuestionAttachmentsCount); //DEBUG
                console.log("totalQuestionAttachmentsCount: " + totalQuestionAttachmentsCount); //DEBUG
                if (uploadedQuestionAttachmentsCount == totalQuestionAttachmentsCount) {
                    alert("DEBUG: All Question Attachments Uploaded."); //DEBUG
                }
            }
        }
    });
	updForQuestion = uploaderForQuestion;
}
window.onload = createUploader;

function uploadQuestionAttachments() {
    totalQuestionAttachmentsCount = updForQuestion._storedFileIds.length;
    updForQuestion.uploadStoredFiles();
}