我们知道文件无法通过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'),
最佳答案
为了给您提供另一种选择,有几个使用 jquery 编写的优秀文件 uploader 。我推荐Uploadify如果你愿意尝试其他的。但是,此 uploader 确实需要 Flash。
编辑: 我不知道这个 uploader 如何使用ajax工作;它可以像 Sheen 提到的那样在 html5 中完成。但是,通过在 stackoverflow 上进行一些搜索,您似乎可以尝试此操作以使其与 jquery 选择器一起使用:
element: $('#upload')[0];
我从问题 document-getelementbyid-vs-jquery 中找到了这个解决方案
关于jquery - 为什么这个插件可以通过ajax上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7135887/