簡體   English   中英

php圖像文件上傳並轉換為base64而不保存圖像

[英]php image file upload and convert to base64 without saving image

我知道如何上傳圖像文件並使用以下代碼保存到其他位置。 但是,我需要這樣做,用戶上傳圖像並自動轉換為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>

您的代碼中存在錯誤:

$data = file_get_contents( $file_ext );

這應該是:

$data = file_get_contents( $file_tmp );

這應該可以解決您的問題。

暫無
暫無

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

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