hi,
i try to upload a picture taken with Camera to a server and handle it in PHP.
- i take the picture
- the image data is converted to a base64 encoded string by calling a C++ function exposed to QML
QString ImageUrl2Base64::getImageDataByUrl(QString url) { QFile fileImg(url); fileImg.open(QIODevice::ReadOnly); QByteArray imageData = fileImg.readAll(); QByteArray imageData_Base64 = imageData.toBase64(); QString imgdata(imageData_Base64); return imgdata; }
- the encoded data is posted using XMLHttpRequest
function post2Server(fname,img) { var url = "http://server"; var params = "filename=" + fname + "&imgdata=" + img; var xhr = new XMLHttpRequest(); xhr.open('POST', url, false); //-- headers xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Content-length", params.length); xhr.setRequestHeader("Connection", "close"); xhr.onreadystatechange = (function(myxhr) { return function() { if(myxhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) { // console.log(myxhr.responseText) } else if( myxhr.readyState === XMLHttpRequest.DONE) { if (myxhr.status === 200) { console.log(myxhr.responseText) // var data = JSON.parse(myxhr.responseText); if(data !== null ) { //cb(data); } } else { console.log(myxhr.responseText) } } } })(xhr); xhr.send(params); }
- on server i decode it using a php script
<?php $upload_dir = "../upload/"; $fname = $_POST['filename']; $img = $_POST['imgdata']; $img=substr($img, strpos($img, ",")+1); $img = str_replace(' ', '+', $img); $data = base64_decode($img); $file = $upload_dir . "" .basename($fname); $success = file_put_contents($file, $data); print $success ? $file : 'Unable to save the file.'; ?>
the image data on server is corrupted, and when i compare the image data from taken picture and server image are different.
is this the right way to do it?
i could not find anything simpler.
thanx!