Skip to content

Instantly share code, notes, and snippets.

@iraniamir
Created August 21, 2018 13:00
Show Gist options
  • Save iraniamir/c0fe07a41195c425e089692a782db13e to your computer and use it in GitHub Desktop.
Save iraniamir/c0fe07a41195c425e089692a782db13e to your computer and use it in GitHub Desktop.
Chunk upload file
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Fanap Drive Upload</title>
</head>
<body>
<input id="fileupload" type="file" name="file" />
<span>Percentage : %
<span id="per">0</span>
</span>
<script src="jquery.min.js"></script>
<script src="md5.js"></script>
<script>
$(function () {
var chunkSize = 1e6; // 1MB
$('#fileupload').change(function () {
if (!this.files.length) return;
var fr = new FileReader(),
file = this.files[0];
fr.onload = function (e) {
splitAndSendFile(e.target.result, file);
};
fr.readAsArrayBuffer(file);
});
async function splitAndSendFile(dataArray, file) {
var i = 0,
chunks = Math.ceil(file.size / chunkSize),
chunkCount = 0,
hash = "0",
percentage = 0,
percentageElm = $("#per"),
formData, blob;
var eachChunkPer = 100 / chunks;
// var md5 = CryptoJS.MD5(dataArray).toString();
// console.log("CheckSum : ", md5);
console.log("Chunks : ", chunks);
dataArray = new Uint8Array(dataArray);
for (; i < dataArray.length; i += chunkSize) {
console.log("State : ", chunkCount);
blob = new Blob([dataArray.subarray(i, i + chunkSize)]);
formData = new FormData();
formData.append("file", blob, file.name);
formData.append("name", file.name);
formData.append("chunk", chunkCount);
formData.append("chunks", chunks);
formData.append("hash", hash);
await $.ajax({
async: true,
crossDomain: true,
url: 'http://192.168.10.102:8083/nzh/drive/uploadChunkFile/?_token_=b68db8ab5711490f867e7bf0322ead96&_token_issuer_=1',
type: 'POST',
headers: {},
data: formData,
processData: false,
contentType: false,
mimeType: "multipart/form-data",
success: function (bla, msg) {
if (chunkCount == 0) {
var json = JSON.parse(bla);
hash = json.result.hash;
percentage += eachChunkPer;
percentageElm.html(percentage);
}
chunkCount++;
},
error: function (bla, msg) {}
});
}
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment