解码base64图像并使用php将其上载到服务器

解码base64图像并使用php将其上载到服务器,php,base64,Php,Base64,我将图像作为base64字符串从表单传递。然后我想解码它,重命名它,并上传到我的服务器文件夹。我不能让它工作,所以很明显我做错了什么。任何帮助都将不胜感激 我的代码: $image = $_POST['image-data'];//base64 string of a .jpg image passed from form: $image = str_replace('data:image/png;base64,', '', $image);//Getting rid of the start

我将图像作为base64字符串从表单传递。然后我想解码它,重命名它,并上传到我的服务器文件夹。我不能让它工作,所以很明显我做错了什么。任何帮助都将不胜感激

我的代码:

$image = $_POST['image-data'];//base64 string of a .jpg image passed from form:

$image = str_replace('data:image/png;base64,', '', $image);//Getting rid of the start of the string:
$image = str_replace(' ', '+', $image);
$image = base64_decode($image);

$ext = strtolower(substr(strrchr($image, '.'), 1)); //Get extension of image

$lenght = 10;
$image_name = substr(str_shuffle("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ"), 0, $lenght);

$image_name = $image_name . '.' . $ext; //New image name

$uploaddir = '/var/www/vhosts/mydomain.com/httpdocs/img/'; //Upload image to server
$uploadfile = $uploaddir . $image_name;
move_uploaded_file('$image', $uploadfile);

使用文件放置内容,您可以将文件移动到文件夹

$file = $_POST['image-data'];
$pos = strpos($file, ';');
$type = explode(':', substr($file, 0, $pos))[1];
$mime = explode('/', $type);

$pathImage = "path to move file/".time().$mime[1];
$file = substr($file, strpos($file, ',') + 1, strlen($file));
$dataBase64 = base64_decode($file);
file_put_contents($pathImage, $dataBase64);

为什么在上传之前要转换文件?关于如何在php中处理文件上载的更多信息您不能使用move_upload_file(您没有上载任何文件)。您的图像数据显示为字符串。我认为您必须从字符串资源创建一个图像。oder Imagick是你的朋友;)然后将图像另存为文件到“上载目录”中。这看起来很有希望。但是,我从这一行中得到了错误消息:
$type=explode(“:”,substr($file,0,$pos))[1]