PHP图像文件上传并转换为Base64,无需保存图像

26

我知道如何上传图像文件并将其保存到其他位置,使用以下代码。但是,我需要以这样一种方式进行操作:用户上传图像并自动转换为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>

图片转换为base64后,您希望发生什么? - Pekka
4
使用 file_get_contents() 函数获取临时上传文件的内容,使用 base64_encode() 进行编码,使用 file_put_contents() 函数保存该文件。虽然存储图像文件的 base64 编码表示似乎不是一个好主意 - 对于大文件,你可能会遇到内存问题,并且生成的文件将比原始文件大 33%。为什么要这样做? - Pekka
那应该没问题,你得到了什么?(请注意,为了获得更完美的解决方案,你应该通过比文件扩展名更安全的方式检测图像类型,例如使用 getimagesize() - Pekka
这是因为我认为用户上传时我正在使用图像的临时目录,所以我遇到了这个错误。我应该如何更改?警告:file_get_contents(jpg)[function.file-get-contents]:无法打开流:在/Applications/XAMPP/xamppfiles/htdocs/uploadimage/index.php的第21行中没有这样的文件或目录。 - Khant Thu Linn
3
file_get_contents($file_ext):你没有使用$file_tmp - Pekka
显示剩余9条评论
1个回答

21

你的代码中有一个错误:

$data = file_get_contents( $file_ext );
这应该是:

这应该是:

$data = file_get_contents( $file_tmp );

这应该解决你的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接