【问题标题】:PHP: Encode image Base64 localPHP:编码图像 Base64 本地
【发布时间】:2014-06-09 06:43:01
【问题描述】:

我想将图像转换为 Base64 并放入我的数据库。 我知道如何将图像编码为 Base64,但我不知道如何使用来自用户的文件。

因此用户可以使用<input type="file" />“上传”文件 但是如何在不下载文件并将其存储在我的服务器上的情况下处理该文件?

所以我在用户他/她的计算机上实际本地编码文件

谢谢

【问题讨论】:

  • 简而言之:你不能。这是内置于 http 服务器的安全限制。以这种方式上传的每个文件都将保存到一个临时文件中,您对此无能为力,除了访问该临时文件来处理文件数据之外别无他法。这是故意的。
  • 为什么要在client端编码?由于用户可能不愿意理解并执行此操作,您必须在脚本级别 (javascript) 自动执行此操作,但是 为什么
  • @arkascha 这不是 web 服务器做的,是 php 模块将上传的文件保存到临时路径中。
  • @Jack:php 模块,正如它的名字“模块”已经说过的,在 http 服务器进程的范围内执行。将 php 模块想象成一个库,或者更好地作为 http 服务器的插件。所以是的,这里的活动实例“做”的事情 http 服务器。
  • @arkascha 不,执行工作的活动实例 php 模块;文件上传从其指定的输入流中读取;这也是is_uploaded_file() 知道当前请求中上传了哪个文件的方式。

标签: php file base64 local-storage local


【解决方案1】:
<input type="file" name="icon" />

现在试试下面的代码。

 $base  =  $_REQUEST['icon'];
 $binary   =  base64_decode($base);
 header('Content-Type: bitmap; charset=utf-8');
 $file  = fopen('upload/imagename.png', 'wb');
 $imagename = 'path_to_image_/images.png';
 fwrite($file, $binary);
 fclose($file);

【讨论】:

    【解决方案2】:

    要将图像编码为 base64,您可以使用 file_get_contents 来读取图像文件:

    $imageBinaryString = file_get_contents('/image/file/path.png');
    

    http://us1.php.net/file_get_contents

    然后base64编码:

    $base64_imageString = base64_encode($imageBinaryString);
    

    然后您可以在数据库中存储类型为 text 或 varchar 的列。

    【讨论】:

      【解决方案3】:

      BLOB 数据类型最适合存储文件。

      如果您不想将文件保存到数据库中,而只是读取它,请使用:

      <form method="post" enctype="multipart/form-data">
      <table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
      <tr> 
      <td width="246">
      <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
      <input name="userfile" type="file" id="userfile"> 
      </td>
      <td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
      </tr>
      </table>
      </form>
      

      <?php
      if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
      {
      $fileName = $_FILES['userfile']['name'];
      $tmpName  = $_FILES['userfile']['tmp_name'];
      $fileSize = $_FILES['userfile']['size'];
      $fileType = $_FILES['userfile']['type'];
      
      $fp      = fopen($tmpName, 'r');
      $content = fread($fp, filesize($tmpName));
      $content = addslashes($content);
      fclose($fp);
      

      $content 这里有文件内容

      【讨论】:

      • BLOB 数据类型不适合这个项目。因为我想让我的数据库尽可能小(在存储中)。
      • @user3322384 Base64 编码文件占用更多空间;如果您想让数据库尽可能小,不要在其中存储图像。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      相关资源
      最近更新 更多