出于一些奇怪的原因,使用MS Graph API的大文件上传无法在Edge和IE上运行,但是从Chrome开始工作就好了,并且符合预期。
var auth = 'Bearer 123';
var theFile;
function getSessionUrl(filename){
return `https://graph.microsoft.com/v1.0/drives/<driveid>/items/<itemid>/children/${filename}/createUploadSession`;
}
function chunkedUpload(url,
file,
chunkSize = 327680,
chunkStart = 0,
chunkEnd = chunkSize,
chunks = file.size / chunkSize,
chunksDone = 0,
fileChunk = file.slice(chunkStart, chunkEnd)) {
let req = new XMLHttpRequest(),
fileReader = new FileReader();
req.open("PUT", url, true);
req.setRequestHeader("Authorization", auth);
req.setRequestHeader("Content-Range", "bytes " + chunkStart + "-" + (chunkEnd - 1) + "/" + file.size.toString());
req.onload = (e) => {
let response = JSON.parse(req.response);
if (response.nextExpectedRanges) {
let range = response.nextExpectedRanges[0].split('-'),
chunkStart = Number(range[0]),
nextChunk = chunkStart + chunkSize,
chunkEnd = nextChunk > file.size ? file.size : nextChunk;
console.log(((chunksDone++/ chunks) * 100), '%' );
chunkedUpload(url, file, chunkSize, chunkStart, chunkEnd, chunks, chunksDone);
} else {
console.log("upload session complete");
}
};
fileReader.onload = function(fileLoadedEvent) {
req.send(this.result);
};
fileReader.readAsArrayBuffer(fileChunk);
}
$("#file").change((event) => {
var file = event.target.files[0];
theFile = file;
});
$("#send").click(() => {
var url = getSessionUrl(theFile.name);
$.ajax({
type: "POST",
url: url,
headers: {
authorization: auth
},
success: (data) => {
chunkedUpload(data.uploadUrl, theFile);
}
});
});
代码是可执行的,但要重现错误,您必须使用适当的授权令牌auth
和<driveid>
替换<itemid>
,并使用与您的OneDrive相对应的适当ID。