解码base64图像并使用php将其上传到服务器
问题描述:
我从图像传递图像作为base64字符串。然后我想解码它,重命名并上传到我的服务器文件夹。我无法得到这个工作,所以显然我在这里做错了什么。任何帮助,将不胜感激。解码base64图像并使用php将其上传到服务器
我的代码:
$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中处理文件上传的信息http://php.net/manual/en/features.file-upload.php – jeff
你不能使用move_upload_file(你没有上传任何文件)。您的图像数据以字符串形式出现。我认为你必须从字符串资源中创建一个图像。 GD或者Imagick是你的朋友;)然后将图像保存为你的'上传目录'文件。 – BenRoob