2017-08-31 69 views
0

我從圖像傳遞圖像作爲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); 
+1

爲什麼你之前上傳的文件轉換?更多關於如何在php中處理文件上傳的信息http://php.net/manual/en/features.file-upload.php – jeff

+0

你不能使用move_upload_file(你沒有上傳任何文件)。您的圖像數據以字符串形式出現。我認爲你必須從字符串資源中創建一個圖像。 GD或者Imagick是你的朋友;)然後將圖像保存爲你的'上傳目錄'文件。 – BenRoob

回答

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); 
+0

這看起來很有希望。但是我從這一行收到錯誤信息:'$ type = explode(':',substr($ file,0,$ pos))[1];' – Jqrp

+0

他是什麼錯誤 – Shibon

相關問題