Upload blob data to php server, fetch data from url

I am trying to upload an image to a php server from a mobile application, converting the file to blob and then downloading blob using ajax. After receiving the photo from my mobile, I get the URL of the image. The downloaded file is empty. I think this 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";  

?>
+4
source share
1 answer

Solved to use base64 image with this

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.';
+1
source

Source: https://habr.com/ru/post/1539916/


All Articles