简体   繁体   English

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

[英]Decoding base64 image and uploading it to server with php

I'm passing image as a base64 string from a form.我将图像作为 base64 字符串从表单传递。 Then I would like to decode it, rename it and upload it to my server folder.然后我想解码它,重命名它并将其上传到我的服务器文件夹。 I can't get this to work so obviously I'm doing something wrong here.我不能让它工作,所以很明显我在这里做错了。 Any help would be appreciated.任何帮助将不胜感激。

My code:我的代码:

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

Using file put content you can move files to folder使用文件放置内容,您可以将文件移动到文件夹

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM