簡體   English   中英

解碼base64圖像並使用php將其上傳到服務器

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

我將圖像作為 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM