2013-10-12 74 views
14

我知道如何上傳圖像文件並使用以下代碼保存到其他位置。但是,我需要這樣做,即用戶上傳圖像並自動轉換爲base64,而不將該圖像保存在我的位置。我應該怎麼做?php圖像文件上傳並轉換爲base64而不保存圖像

<?php 
//print_r($_FILES); 
if(isset($_FILES['image'])) 
{ 
    $errors=array(); 
    $allowed_ext= array('jpg','jpeg','png','gif'); 
    $file_name =$_FILES['image']['name']; 
// $file_name =$_FILES['image']['tmp_name']; 
    $file_ext = strtolower(end(explode('.',$file_name))); 


    $file_size=$_FILES['image']['size']; 
    $file_tmp= $_FILES['image']['tmp_name']; 
    echo $file_tmp;echo "<br>"; 

    $type = pathinfo($file_tmp, PATHINFO_EXTENSION); 
    $data = file_get_contents($file_ext); 
    $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data); 
    echo "Base64 is ".$base64; 



    if(in_array($file_ext,$allowed_ext) === false) 
    { 
     $errors[]='Extension not allowed'; 
    } 

    if($file_size > 2097152) 
    { 
     $errors[]= 'File size must be under 2mb'; 

    } 
    if(empty($errors)) 
    { 
     if(move_uploaded_file($file_tmp, 'images/'.$file_name)); 
     { 
     echo 'File uploaded'; 
     } 
    } 
    else 
    { 
     foreach($errors as $error) 
     { 
      echo $error , '<br/>'; 
     } 
    } 
    // print_r($errors); 

} 
?> 


<form action="" method="POST" enctype="multipart/form-data"> 

<p> 
    <input type="file" name="image" /> 
    <input type="submit" value="Upload"> 

</p> 
</form> 
+0

將圖像轉換爲base64後,您希望發生什麼? –

+0

實際上,對於項目,我想將base64保存到數據庫中而不是保存圖像文件。 –

+4

使用'file_get_contents()'獲取臨時上傳文件的內容,'base64_encode()'對其進行編碼,'file_put_contents()'保存文件。雖然存儲圖像文件的base64編碼表示聽起來像一個壞主意 - 對於大文件,您可能遇到RAM問題,並且生成的文件將比原始文件大33%。爲什麼這樣做? –

回答

5

。在你的代碼的錯誤:

$data = file_get_contents($file_ext); 

這應該是:

$data = file_get_contents($file_tmp); 

這應該解決您的問題。

相關問題