Jquery承诺whit对象


function uploadfiles(inputcontrol){ 
//here the function takes all the files of an input files
//for each inputcontrol.files[i]
//createObject(inputcontrol.files[i]);
}
function createObject(files){ 
//this function creates an object with each one of them the files 
//are processed and loaded in a web service whit AJAX
}
when(uploadfiles()).then(alert('All files uploaded'));

当我运行此脚本时,会立即显示警报,并且不会等待文件正确上载。我应该如何运行$.何时运行?

我更新了你的clupload类,这样它就可以使用Deferred对象读取文件,因为我们现在可以链接读取文件然后上传的过程。

我还更改了getBase64函数,使其返回Deferred对象,这样我们以后可以使用donefail方法。

这是代码:

class clupload {
constructor(file, Ticket) {
this.f = file;
this.t = Ticket;
}
readFile () {
var dfd = $.Deferred();
var reader = new FileReader();
reader.onload = function(e) {
dfd.resolve(e.target.result);
};
reader.readAsDataURL(this.f);
return dfd.promise();
}
procesar() {
var tt = this.t;
var nombre = this.f.name;
var user = $('#loginUsrApp').val();
return this.readFile().then(function (salida) {
return $.ajax({
type: "POST",
url: "WebService.asmx/SubirArchivo",
data: "{T:'" + tt + "',b64:'" + salida + "',N:'" + nombre + "',U:'" + user + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json"
})
});
}
}
function getBase64(f, T) {
var files = document.querySelector(f).files;
var uploads = files.map(function (file) {
var upload = new clupload(file, T);
return upload.procesar();
});
return $.when.apply($, uploads);
}

现在你只需要这样称呼它:

getBase64('#upload1', r.d).done(function() {
alert('Guardado');
}).fail(function () {
alert('Error');
});

最新更新