jQuery的阿贾克斯文件上传Facebook的风格 [英] Jquery Ajax File Upload facebook style

查看:95
本文介绍了jQuery的阿贾克斯文件上传Facebook的风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个: http://malsup.com/jquery/form/ ..它的工作不错,但我希望有一个上传进度系统,如Facebook,这里的窗口负载,同时该文件被上传,上传进度显示在浏览器的左下角。是否有这样的jQuery的AJAX表单提交的支持文件上传。

I have one: http://malsup.com/jquery/form/‎ .. It works okay but I want a upload progress system like facebook, where the window loads while the file is uploading and upload progress is shown at the left bottom corner of the browser. Is there any such jquery ajax form submission that supports file uploading.

推荐答案

你可以做到这一点的一个XHRListener。 我做了一些时间之前类似的东西,这里所使用的codeI的一个片段:

you can do that with a XHRListener. i did something similar before some time, here's a snippet of the code i used:

jQuery.ajax({
    url: 'url/to/upload/to',
    data: formMediaData,
    dataType:'json', //return type, in my case it was json
    type: 'post',
    xhr: function(){ 
        // this is the important part
        var xhr = new window.XMLHttpRequest();

        //the event listener will call _very_ often, you might want to check
        // how big the difference between the last percentage and this 
        //percentage is, before you do anything that needs long computing times(!)

        xhr.upload.addEventListener("progress", function(evt){
            //check if the browser can determine the complete size of the data.
            if (evt.lengthComputable) {
                var percentComplete = Math.round((evt.loaded / evt.total)*100);

                //do something with the percentage...

                console.log("upload " +percentComplete + "% done");
            }
        },false);
        return xhr;
    },
    success: function(data){
        //do some tasks after upload
        console.log("upload done");
    }
});

下面是你如何添加文件:

here's how you add files:

HTML:

<!-- accept="image/*" will only accept file miming to be an image, remember to check if it really is an image... -->
<input type="file" id="uploadBox" accept="image/*" onchange="handleMediaFiles(this.files)" />

记者:

var formMediaData= new FormData();

function handleMediaFiles(files){
    for(var i=0;i<files.length;i++){
        formMediaData.append('file_'+i,file[i]);
    }
    fileUpload(); // that's where the ajax is sent  
}

这篇关于jQuery的阿贾克斯文件上传Facebook的风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆