Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload Blob data to php server, retrieving data from url [duplicate]

I'm trying to upload an image to a php server from a mobile app, converting file to blob and then uploading the blob with ajax. I get the image url after taking the photo with mobile. The uploaded file is empty. I think that should be an error while reading the file and converting to blob.

Client

var blob;
function get(){

var image = document.getElementById('image');
var file=image.src;

var oReq = new XMLHttpRequest();
oReq.open("GET", file, true);
oReq.responseType = "arraybuffer";

oReq.onload = function(oEvent) {
   blob = new Blob([oReq.response], {type: "image/jpg"});
};


oReq.send();


var fd = new FormData();
fd.append("file", blob, "filename.jpg");
$.ajax({
    type: 'POST',
    url: 'http://site/upload.php',
    data: fd,
    processData: false,
    contentType: false
}).done(function(data) {
       alert(data);
});

}

Server

<?php
$dir="uploads";

file_put_contents($dir."/image.jpg",$_POST['data']);

    echo "Done";  

?>
like image 287
Gabriele Prestifilippo Avatar asked Nov 01 '22 00:11

Gabriele Prestifilippo


1 Answers

Solved using base64 image with that

define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
like image 94
Gabriele Prestifilippo Avatar answered Nov 10 '22 06:11

Gabriele Prestifilippo