最近我不得实现一个文件异步上传的功能,但是我不想使用Flash或 或者插件,经过一些研究,我想出了这个解决方案。于是分享给大家:

HTML:

<form enctype=\"multipart/form-data\">
    <input name=\"file\" type=\"file\" />
    <input type=\"button\" value=\"Upload\" />
</form>
<progress></progress>

首先,您可以根据需要进行一些验证。例如,在文件的 事件中:

$(\':file\').on(\'change\', function() {
    var file = this.files[0];
    if (file.size > 1024) {
        alert(\'max upload size is 1k\')
    }

    // Also see .name, .type
});

点击按钮并实现AJAX异步上传文件:

$(\':button\').on(\'click\', function() {
    $.ajax({
        // Your server   to process the upload
        url: \'upload.php\',
        type: \'POST\',

        // Form data
        data: new FormData($(\'form\')[0]),

        // Tell jQuery not to process data or worry about content-type
        // You *must* include these options!
        cache: false,
        contentType: false,
        processData: false,

        // Custom  HttpRequest
        xhr: function() {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                // For handling the progress of the upload
                myXhr.upload.addEventListener(\'progress\', function(e) {
                    if (e.lengthComputable) {
                        $(\'progress\').attr({
                            value: e.loaded,
                            max: e.total,
                        });
                    }
                } , false);
            }
            return myXhr;
        },
    });
});

从上面代码你可以看到,HTML5文件上传不仅变得可能而且非常简单。

收藏 打印