I am working on creating a file uploader, where the contents will be written to a remote server in chunks using a 3rd party API. The API provides a WriteFileChunk()
method that takes 3 parameters, the target file path, the start position (Int64) and data (string) of bytes.
Each time FileReader receives a chunk of the maximum supported size (16kb), I need to use Ajax to pass this to a PHP file and write it using the API. I suspect that this should be done in the onprogress
event of FileReader, however I am at somewhat of a loss given that I cannot find any similar examples.
What would be the best way to implement this using FileReader, ensuring that each chunk is uploaded before writing the next? If onprogress
is the best choice, how can I get the current chunk data?
$(document).ready(function()
{
function uploadFile()
{
var files = document.getElementById('file').files;
if (!files.length)
{
alert('Please select a file!');
return;
}
var file = files[0];
var first_byte = 0;
var last_byte = file.size - 1;
// File Reader
var reader = new FileReader();
reader.onerror = function(evt)
{
switch(evt.target.error.code)
{
case evt.target.error.NOT_FOUND_ERR:
alert('File Not Found!');
break;
case evt.target.error.NOT_READABLE_ERR:
alert('File is not readable');
break;
case evt.target.error.ABORT_ERR:
break;
default:
alert('An error occurred reading this file.');
};
};
reader.onprogress = function(evt)
{
if (evt.lengthComputable)
{
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
console.log(percentLoaded + "%");
if (percentLoaded < 100)
{
$("#upload_progress").progressbar('value', percentLoaded);
}
}
};
reader.onabort = function(evt)
{
alert('File Upload Cancelled');
};
reader.onloadstart = function(evt)
{
$("#upload_progress").progressbar({
value: 0,
max: 100
});
};
reader.onload = function(evt)
{
$("#upload_progress").progressbar('value', 100);
};
reader.onloadend = function(evt)
{
if (evt.target.readyState == FileReader.DONE) // DONE == 2
{
alert("Upload Complete!");
//console.log(evt.target.result);
}
};
var blob = file.slice(first_byte, last_byte + 1);
reader.readAsBinaryString(blob);
}
fileupload_dialog = $( "#dialog-fileupload" ).dialog(
{
autoOpen: false,
height: 175,
width: 350,
modal: true,
buttons:
{
"Upload File": uploadFile
},
close: function()
{
form[ 0 ].reset();
}
});
form = fileupload_dialog.find( "form" ).on( "submit", function( event )
{
event.preventDefault();
uploadFile();
});
$("#file_upload a").click(function()
{
event.preventDefault();
fileupload_dialog.dialog( "open" );
});
});