php图像文件上传并转换为base64而不保存图像

标签 php image upload base64

我知道如何使用以下代码上传图像文件并保存到其他位置。但是,我需要以用户上传图像并自动转换为 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 );

这应该可以解决您的问题。

关于php图像文件上传并转换为base64而不保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19335477/

相关文章:

c# - 管理图像?

ios - 是否有可能在一个gestureRecognizer(快速)中触发另一个gestureRecognizer?

Dart、Flutter : upload . jpg 文件到 Google 云端硬盘

php - 从 mysqli select 返回错误的数值

php - 从数据库中的两个表获取信息,其中 id 与数组匹配?

php - Laravel 6 验证 : there is limit in number of rules?

javascript - PhantomJS - 上传文件而不提交表单

php - 接受/拒绝/完成 - 数据库中记录的状态(标志)

c# - Windows 服务 : using of BitmapEncoder or BitmapDecoder ends with «The operation completed successfully»

Maven Assembly 插件,上传正确的 zip 文件