为什么这个插件可以通过ajax上传文件?

时间:2011-08-21 02:00:57

标签: jquery ajax file-upload

我们知道该文件无法通过ajax上传,但我不明白为什么这个ajax upload file plugin使用普通的ajax?

_upload: function(id, params){
        var file = this._files[id],
            name = this.getName(id),
            size = this.getSize(id);

        this._loaded[id] = 0;

        var xhr = this._xhrs[id] = new XMLHttpRequest();
        var self = this;

        xhr.upload.onprogress = function(e){
            if (e.lengthComputable){
                self._loaded[id] = e.loaded;
                self._options.onProgress(id, name, e.loaded, e.total);
            }
        };

        xhr.onreadystatechange = function(){            
            if (xhr.readyState == 4){
                self._onComplete(id, xhr);                    
            }
        };

        // build query string
        params = params || {};
        params['qqfile'] = name;
        var queryString = qq.obj2url(params, this._options.action);

        xhr.open("POST", queryString, true);
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
        xhr.setRequestHeader("Content-Type", "application/octet-stream");
        xhr.send(file);
    }

我不喜欢这个插件,因为你不能将它与jquery一起使用,目标元素必须始终是一个ID,

function createUploader(){            
            var uploader = new qq.FileUploader({
                element: document.getElementById('file-uploader-demo1'),
            action: 'upload-file.php',
                onComplete: function(id, fileName, responseJSON){alert(responseJSON[0].filename)},
                debug: true
            });           
        }

        // in your app create uploader as soon as the DOM is ready
        // don't wait for the window to load  
        window.onload = createUploader;  

如果我可以用jquery做这样的事情,那就是我需要的但是我不知道如何更改源代码,因为它是用简单的javascript编写的!

element: $('.upload'), or  element: $('#upload'),

2 个答案:

答案 0 :(得分:1)

为了给你另一个选择,有几个使用jquery编写的好的文件上传器。如果您愿意尝试其他人,我建议Uploadify。但是,这个上传程序确实需要闪存。

修改 我不知道这个上传器如何使用ajax工作;它可以在像Sheen提到的html5中完成。但是,通过对stackoverflow进行一点搜索,您似乎可以尝试使用它来使用jquery选择器:

element: $('#upload')[0];

我从问题document-getelementbyid-vs-jquery

中找到了这个解决方案

答案 1 :(得分:0)

看起来像html5。您可以通过html5中的ajax进行文件上传。 http://blog.new-bamboo.co.uk/2010/7/30/html5-powered-ajax-file-uploads