Javascript split uploaded file before ajax call

For the fastest file upload, we should bather about uploaded files in ajax call. If the user try to upload large size file then the uploading time will be like ¯\_(ツ)_/¯ .

So that we have to check the file size before sending, If it’s a large one then split the file and send with ajax call with formData().

We have already discussed some thing about FileReader(). Here we will use this FileReader() for getting uploaded file and read the file content and split it to some number of ~5MB size file.

var uploadFile = document.getElementById("upload-file");
uploadFile.addEventListener("change", function(event) {
	var fr = new FileReader(), file = event.target.files[0];
	fr.onload = function(e) {
		splitAndSendFile(new Uint8Array(e.target.result), file);
	};
	fr.readAsArrayBuffer(file);
}
function splitAndSendFile(dataArray, file) {
	var i = 0,
	splitSize = (1e6*5),// ((10^6)*5) = 5000000 Bytes 
	splitedData,
	blob;
	for (; i < dataArray.length; i += splitedSize) {
		blob = new Blob([dataArray.subarray(i, i + splitedSize)]);
		splitedData = new FormData();
		splitedData.append("splitedFiles", blob, file.name + ".part" + (i / splitedSize));
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = function() {
		  if (xmlhttp.readyState === 4) {
			  if (xmlhttp.status === 200) {
				  alert("success");
			  } else {
				  alert("Error!");
			  }
		  }
		};
		xmlhttp.open("POST", url, true);
		xmlhttp.send(splitedData);
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *