[英]Using xhr object for html5 chunked upload in a loop
专家,我在为可恢复的分块上传创建的BLOB块中循环时遇到了问题。 我要遵循的方法是:我使用Blob.slice()对要上传的文件进行分块,将所有分块推送到队列中,然后尝试将它们发送到我的服务器。
我面临的问题是关于遍历各个块。 第一个块已成功发送,最后我从委托给xhr.onreadystatechange的函数中使用了下面提到的uploadNext方法。 到目前为止一切都很好,但是这段代码只是在发送了前两个块之后才停止,并且不会循环通过。
到目前为止,以下代码是我已经实现的:
uploadFile: function(item, location, start, isresume) {
var blob = item.file;
const BYTES_PER_CHUNK = 1024 * 200 * 10;
const SIZE = blob.size;
var chunkId = 0;
var end = BYTES_PER_CHUNK;
while(start < SIZE) {
var chunkObj = {};
// Note: blob.slice has changed semantics and been prefixed. See http://goo.gl/U9mE5.
end = start + BYTES_PER_CHUNK;
if(end > SIZE){
end = SIZE;
}
if ('mozSlice' in blob) {
chunkObj["chunk"] = blob.mozSlice(start, end);
chunkObj["id"] = chunkId;
} else {
// var chunk = blob.webkitSlice(start, end);
chunkObj["chunk"] = blob.slice(start, end);
chunkObj["start"] = start;
chunkObj["end"] = end-1;
chunkObj["id"] = chunkId;
}
chunkId++;
item.chunks.push(chunkObj);
start = end ;
}
this.upload(item, location, SIZE, isresume);
},
upload: function(item, location, SIZE, isresume) {
var xhr = new XMLHttpRequest();
// Upload the first chunk
xhr.upload.addEventListener("error", this.onFileUploadError.createDelegate(this, [item, xhr], 0), false);
xhr.onload = this.getStatus.createDelegate(this, [item, xhr, isresume], 0);
xhr.onreadystatechange = this.isChunkUploaded.createDelegate(this, [item, item.chunks[0], xhr, 0, SIZE, location, isresume], 0);
xhr.open("PUT", location, true);
xhr.setRequestHeader("Content-Range", "bytes " + item.chunks[0].start + "-" + item.chunks[0].end + "/" + SIZE);
xhr.send(item.chunks[0].chunk);
},
uploadNext: function(item, xhr, index, SIZE, location, isresume) {
if(index > item.chunks.length) {
return;
}
console.log("uploading next chunk");
xhr = new XMLHttpRequest();
xhr.upload.addEventListener("error", this.onFileUploadError.createDelegate(this, [item, xhr], 0), false);
xhr.onload = this.getStatus.createDelegate(this, [item, xhr, isresume], 0);
xhr.onreadystatechange = this.isChunkUploaded.createDelegate(this, [item, xhr], 0);
xhr.open("PUT", location, true);
xhr.setRequestHeader("Content-Range", "bytes " + item.chunks[index].start + "-" + item.chunks[index].end + "/" + SIZE);
xhr.send(item.chunks[index].chunk);
//this.uploadNext(item, xhr, index + 1, SIZE, location, isresume);
},
isChunkUploaded: function(item, chunkObj, request, index, SIZE, location, isresume, e) {
if (request.readyState === 4) {
console.log("chunk " + index + " uploaded");
this.uploadNext(item, request, index + 1, SIZE, location, isresume);
}
},
PS我不能使用jQuery的相同(不要问为什么)。
没关系,这工作正常。 通过发送比预期少的函数参数作为函数参数,最终犯了一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.