【问题标题】:Jquery Ajax File Upload facebook styleJquery Ajax 文件上传 facebook 样式
【发布时间】:2014-03-06 11:46:27
【问题描述】:

我有一个:http://malsup.com/jquery/form/‎ .. 它工作正常,但我想要一个像 facebook 这样的上传进度系统,在文件上传时加载窗口,上传进度显示在浏览器的左下角。有没有这种支持文件上传的jquery ajax表单提交。

【问题讨论】:

    标签: jquery ajax ajaxform


    【解决方案1】:

    您可以使用 XHRListener 来做到这一点。 我之前做过类似的事情,这是我使用的代码的 sn-p:

    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");
        }
    });
    

    添加文件的方法如下:

    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)" />
    

    js:

    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  
    }
    

    【讨论】:

    • 谢谢。如何附加上传到“formMediaData”的文件?
    • 或者换句话说:“我不想编写任何代码,只要给我代码”? ...我会更新答案....
    • ajax 调用也应该有processData: falsecontentType: false
    • @Mr.Manhattan So?!
    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多