5

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";  

?>
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

3

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.';
  • Would you please post the full client and server code? How can I pass my Blob in the URL format blob:chrome-extension://kllkepcdildfdhlnieemaolmnbkafgjc/b7bdfb7a-9153-4c82-a485-48b137091d63 or with the file name b7bdfb7a-9153-4c82-a485-48b137091d63.webm – Alaa Sadik Jan 26 '21 at 22:27