2014年2月15日星期六

基于AJAX和jQuery上传文件

以前经常用form的方式上传文件,

 如 html:
<form action="your_url" method="post" enctype="multipart/form-data">
    <input name="file" type="file" />
    <button type="submit" value="Upload" />
</form>

或者,想不用点button直接上传的话可以 html:
<form action="url" method="post" enctype="multipart/form-data">
  <input name="file" type="file" />
</form>

加上jQuery:
$('input:file').change(function() {
  $('form').submit();
});

--------------------------分割线---------------------------

但是用Ajax上传文件实在比用form好太多:发送的数据可以很简洁很flexible,
可以在整个上传的过程返回状态,很多处理都放在client上进行,
也不用重新加载整个页面等等。虽然还有一些古董版的浏览器不支持,但现在应该能给绝大部分人用到了。

这里就给个简单的例子吧,先是html:
<form enctype="multipart/form-data">
    <input name="file" type="file" />
</form>

然后是jQuery:
$('input:file').change(function() {
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'your_url',
        type: 'POST',
        data: formData,
    });
});

就OK了。

再来个进阶版的:
$('input:file').change(function() {
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'your_url',
        type: 'POST',
        data: formData,
       beforeSend: function({
         alert('start');
       },
       success: function({
         alert('success');
       },
       error: function({
         alert('failed');
       },
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){  // For handling the progress of the upload
              myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
            }
            return myXhr;
        },
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});
function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

最后,如果想功能更加丰富的话,推荐几个plugin:
1. FineUploader,已经更新到4.3了,慎用4.0以下的版本,有不少bugs;
2. jQuery File Upload, 适合批量上传。