I have a Javascript canvas and I have drawn on it.
After I finished the drawing I click "Save" and an ajax post is sent to the server with the canvas being converted to base64 image.
The image size can be large and I want to display the percentage of upload being done. I can clearly see the POST body size on the firebug post dialog. How can I ask the php about how much post size I have received so far, so I can calculate the percentage? My code so far is:
$.ajax({
async:true,
cache: false,
type: "POST",
data: {
imgData:canvas.toDataURL()
},
url: "/saveImg",
success: function(data) {
console.log('Upload done';)
},
});
And my PHP side is
$fName= uniqid();
$UPLOAD_DIR= 'custom/';
$img = $_POST['imgData'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $UPLOAD_DIR .$fName . '.png';
$success = file_put_contents($file, $data);
EDIT
It looks like using
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
console.log(evt);
if (evt.lengthComputable) {
var percentComplete = parseInt((evt.loaded / evt.total) * 100);
console.log("Upload: " + percentComplete + "% complete")
}
}, false);
return xhr;
},
Kinda works, the result is a 2% and 99% instantly, then a 2 minute pause and then a 100%...
After some experimentation it really matters what i put inside
dataType: 'text',
mimeType: 'text/plain; charset=x-user-defined',
Any ideas? What would have been base64 compatible? Text is not as it seems
I think splitting the text might work.