Aniket Singh Aniket Singh - 5 months ago 42
PHP Question

How to upload base64 encoded image to server

I have jquery plugin which send image in base 64 encoded format which i want to store in server

here is what I've tried

$post = json_decode($_POST['file'], true); $data = $post['output']['image'];

$data = str_replace('data:image/png;base64,', '', $data);

$data = str_replace(' ', '+', $data);

$data = base64_decode($data);

require('/home/example/public_html/files/image/class.upload.php');

$code = md5(time());
$handle = new upload($data);
if ($handle->uploaded) {
$handle->file_new_name_body = "$code";
$handle->mime_check = true;
$handle->allowed = array('image/*');
$handle->image_convert = 'jpg';
$handle->jpeg_quality = 70;
$handle->image_resize = true;
$handle->image_x = 600;
$handle->image_ratio_y = 600;
$handle->process('/home/example/public_html/files/blog/img/');
if ($handle->processed) {
$file_name = $handle->file_dst_name;
} else {
echo "error";
}
}


My above code image upload class works on every image but i'm unable to uploade base 64 encoded image, how can i achieve that

Ian Ian
Answer

The upload class you're using doesn't support feeding base64 directly into it. You're best off using this method to save a temporary version to your directory first, using the class to do what you need to do, then deleting it:

$data = str_replace('data:image/png;base64,', '', $data);

$data = str_replace(' ', '+', $data);

$data = base64_decode($data);

require('/home/example/public_html/files/image/class.upload.php');

$code = md5(time());   
$write_dir = "/home/example/public_html/files/blog/img/";
$temp_code = "temp_".$code;

$ifp = fopen($write_dir.$temp_code, "wb"); 
fwrite($ifp, $data); 
fclose($ifp); 

$handle = new upload($write_dir.$temp_code);
if ($handle->uploaded) {
    $handle->file_new_name_body = "$code";
    $handle->mime_check = true;
    $handle->allowed = array('image/*');
    $handle->image_convert = 'jpg';
    $handle->jpeg_quality = 70;
    $handle->image_resize         = true;
    $handle->image_x              = 600;
    $handle->image_ratio_y        = 600;
    $handle->process($write_dir);
    if ($handle->processed) {
        $file_name = $handle->file_dst_name;
        unlink($write_dir.$temp_code);
    } else {
        echo "error";
    }
}