84 lines
1.9 KiB
JavaScript
84 lines
1.9 KiB
JavaScript
|
const form = document.getElementById("userform")
|
||
|
const submit = document.getElementById("submit")
|
||
|
const results = document.getElementById("results")
|
||
|
|
||
|
const chunksize = 1000000;
|
||
|
|
||
|
const splitter = (file, hash) => {
|
||
|
let numberofChunks = Math.ceil(file.byteLength/chunksize);
|
||
|
let left = 0
|
||
|
let chunks = []
|
||
|
|
||
|
for (let i = 0; i < numberofChunks; i++) {
|
||
|
const chunkForm = new FormData();
|
||
|
let contentRange = "";
|
||
|
let chunk;
|
||
|
if(left+chunksize <= file.byteLength){
|
||
|
contentRange = `${left}-${left+chunksize}`
|
||
|
chunk = file.slice(left,left+chunksize)
|
||
|
left += chunksize
|
||
|
} else {
|
||
|
contentRange = `${left}-${file.byteLength}`
|
||
|
chunk = file.slice(left,file.byteLength)
|
||
|
}
|
||
|
chunkForm.append('file', new Blob([chunk], {type:"video/webm"}))
|
||
|
|
||
|
chunks.push(
|
||
|
fetch("/test", {
|
||
|
method: "POST",
|
||
|
headers: {
|
||
|
"Content-Number": i,
|
||
|
"Content-Range": `bytes ${contentRange}/${file.byteLength}`,
|
||
|
"File-Hash": hash
|
||
|
},
|
||
|
body: chunkForm
|
||
|
}))
|
||
|
|
||
|
}
|
||
|
return chunks
|
||
|
}
|
||
|
|
||
|
async function digest(data){
|
||
|
|
||
|
const hash = await crypto.subtle.digest("SHA-256", data);
|
||
|
return hash
|
||
|
|
||
|
}
|
||
|
|
||
|
const processFile = file => {
|
||
|
const fr = new FileReader()
|
||
|
fr.readAsArrayBuffer(file)
|
||
|
|
||
|
fr.addEventListener("loadend", e => {
|
||
|
|
||
|
digest(e.target.result).then(digestBuffer => {
|
||
|
|
||
|
const hashAsString = Array.from(new Uint8Array(digestBuffer)).map((b) => b.toString(16).padStart(2, "0")).join(""); // hex the buffer for readability
|
||
|
|
||
|
Promise.all(splitter(e.target.result,hashAsString))
|
||
|
.then((values) => {
|
||
|
fetch(`/finish`, {
|
||
|
method: "POST",
|
||
|
headers: {
|
||
|
"Content-Type": "json",
|
||
|
},
|
||
|
body: JSON.stringify({"hash": hashAsString, "type": file.type})
|
||
|
})
|
||
|
})
|
||
|
})
|
||
|
})
|
||
|
|
||
|
}
|
||
|
|
||
|
submit.addEventListener("click", e => {
|
||
|
e.preventDefault();
|
||
|
let fd = new FormData();
|
||
|
|
||
|
for (const file of form.media.files){
|
||
|
|
||
|
processFile(file)
|
||
|
|
||
|
fd.append('file', file)
|
||
|
console.log(file)
|
||
|
}
|
||
|
})
|