【问题标题】:Decode image base64 codeigniter and save it into file and database解码图像base64 codeigniter并将其保存到文件和数据库中
【发布时间】:2017-01-11 07:42:33
【问题描述】:

我想制作一个 codeigniter 控制器,它可以检索“POST”base64 图像,对其进行解码,然后将其保存到本地文件夹中,然后将该路径放入我的 MySQL。

我被困在这一点上。

你能给我一些关于这个案例的参考吗?

【问题讨论】:

  • 我真的建议您在决定这样做之前阅读this thread。祝你好运

标签: php mysql codeigniter base64


【解决方案1】:

以下代码 sn-p 是来自 CodeIgniter 官方用户文档的复制粘贴。

<?php

class Upload extends CI_Controller {

        public function __construct()
        {
                parent::__construct();
                $this->load->helper(array('form', 'url'));
        }

        public function index()
        {
                $this->load->view('upload_form', array('error' => ' ' ));
        }

        public function do_upload()
        {
                $config['upload_path']          = './uploads/';
                $config['allowed_types']        = 'gif|jpg|png';
                $config['max_size']             = 100;
                $config['max_width']            = 1024;
                $config['max_height']           = 768;

                $this->load->library('upload', $config);

                if ( ! $this->upload->do_upload('userfile'))
                {
                        $error = array('error' => $this->upload->display_errors());

                        $this->load->view('upload_form', $error);
                }
                else
                {
                        $data = array('upload_data' => $this->upload->data());

                        $this->load->view('upload_success', $data);
                }
        }
}
?>

CodeIgniter 确实有 built-in file upload class 有非常好的文档,我真的建议你快速浏览一下。

您必须仔细检查的部分或修改如下所示:

$config['file_name']            = 'a_'.md5(microtime()).'.jpg';

它告诉 codeigniter 将文件保存在您想要的任何本地路径中的哪个位置,然后您可以从这里简单地将其保存到您的数据库中,如下所示:

$result = $this->db->query('INSERT INTO AVATARS VALUES (NULL, 'user1', '" . $config['file_name'] . "') ');

请注意,这只是伪代码,尚未在任何生产环境中进行测试;然而,应该完美地工作。

祝你好运

【讨论】:

    【解决方案2】:

    $base 应该有一个 base64 编码的图像字符串:

    $base = $_POST["profile_image"];
    $filename = $_POST["file_name"];
    $filename = $_POST["user_id"];
    $binary = base64_decode($base);
    header('Content-Type: bitmap; charset=utf-8');
    $file = fopen('./Images/'.$filename, 'wb');
    fwrite($file, $binary);
    fclose($file);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多