如何上传base64编码的图片到服务器

How to upload base64 encoded image to server

我有 jquery 插件,它以 base 64 编码格式发送我想存储在服务器中的图像

这是我试过的方法

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

我上面的代码图片上传 class 适用于每张图片,但我无法上传 base 64 编码的图片,我该如何实现

您使用的上传 class 不支持将 base64 直接输入其中。你最好先使用 this method 将临时版本保存到你的目录,使用 class 做你需要做的,然后删除它:

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