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

时间:2017-08-31 12:13:50

标签: 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 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);

1 个答案:

答案 0 :(得分:1)

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

$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);