Javascript Slice uploaded file before ajax call

We have already discussed about Javascript Split Uploaded File Before Ajax Call. Here another method Blob.slice() is used to split the uploaded file. This mehtod is used to create new blob from source blob with data in the specified range. With this slice() method we can add mime type / content type also for our sliced object. default content type is application/octet-stream.

Syntax
instanceOfBlob.slice([start [, end [, contentType]]]); it will return a blob.

Example

var uploadFile = document.getElementById("upload-file");
uploadFile.addEventListener("change", function(event) {
  var file = event.target.files[0];
  var sliceSize = (1e6*5);// ((10^6)*5) = 5000000 Bytes 
  slicedFiles = sliceAndSendFile(file, file.size, sliceSize);
  
  for(var i=0;i<slicedFiles.length;i++){
	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(slicedFiles[i]);
  }
  
}

function sliceAndSendFile(uploadFile, fileSize, sliceSize){
	var i, j, k;
	var slicedBlob = [];
	if (!(uploadFile.slice || uploadFile.mozSlice)) {
		return uploadFile;
	}
	for (i = j = 0, k = Math.ceil(fileSize / sliceSize); 0 <= k ? j < k : j > k; i = 0 <= k ? ++j : --j) {
		if (uploadFile.slice) {
			slicedBlob.push(uploadFile.slice(i * sliceSize, (i + 1) * sliceSize));
		} else if (uploadFile.mozSlice) {
			slicedBlob.push(uploadFile.mozSlice(i * sliceSize, (i + 1) * sliceSize));
		}
	}
	return slicedBlob;
}

Leave a Reply

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