Javascript chunked file upload to PHP Server -
so have function in javascript send parts of file server:
function ajaxpartupload(url, packageno, file, attachmentid) { var packagemaxsize = 10240; //1048576; //10485760; //reduced tests var packagecount = math.ceil(file.size / packagemaxsize); var start = packageno * packagemaxsize; var stop = (packageno+1) * packagemaxsize - 1; if ((packageno+1) === packagecount || packagecount === 0) { stop = file.size - 1; } var blob = file.slice(start, stop); var reader = new filereader(); reader.onloadend = function (evt) { if (evt.target.readystate === filereader.done) { var info = { blob: reader.result, partno: packageno, lastpartno: packagecount, filename: file.name, filetype: file.type, filesize: file.size, attachmentid: attachmentid, multipart: true }; $.ajax({ url: url, type: 'post', datatype: 'json', data: data, success: function(response) { if (response.continue === false) { homecoming true; } else { ajaxpartupload(url, packageno+1, file, response.attachmentid); } } }); } }; reader.readasbinarystring(blob); }
and it's working expected, in post binary info of files i'm sending. under specified url have script basicly this:
$attachment = v()->attachment->find($_post['attachmentid']); $destination_path = $attachment->getpath(); $filepointer = fopen($destination_path, 'a'); $written = fwrite($filepointer, $_post['blob']); if ($written == false ) { throw new exception('file info not written'); } fclose($filepointer);
and long have text files it's ok, when seek send binary file, files i'm reciving 50% bigger in size, , corrupted, doesn't matter if create chunk size big plenty hold file in 1 http request or not. i'm doing wrong?
i have dumped length of 'blob' in javascript right before send , length of recived blob in php: i've got 2 compleatly diffrent results 1 chunk max 1 mb file has '28kb' (got ls -lash):
javascript: 25755
php: 36495
what happend? when i've tired text file ok.
@edit: solution in js change:
blob: reader.result,
to
blob: window.btoa(reader.result),
and in php
$written = fwrite($filepointer, $_post['blob']);
to
$written = fwrite($filepointer, base64_decode($_post['blob']));
that solves problem.
i've added atob in javascript on result reader, , decoded info before reading base64_decode. solves problem.
the problem php interprets binary info in other way, string perhaps, don't know. anyway sending 'bit' bigger encoded info saves lot of nerves.
javascript php ajax file-upload fileapi
No comments:
Post a Comment