【问题标题】:How upload photo in database CI [duplicate]如何在数据库 CI 中上传照片 [重复]
【发布时间】:2017-10-31 10:22:53
【问题描述】:

我对如何在数据库CI中上传照片有疑问,之前我搜索了如何上传照片但没有成功。

这是控制器

 tambah_aksi()
{


    $this->load->library('upload');
    $nmfile = "".time(); //nama file saya beri nama langsung dan diikuti fungsi time
    $config['upload_path'] = './assets/barang/uploads/'; //path folder
    $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; //type yang dapat diakses bisa anda sesuaikan
    $config['max_size'] = '3072'; //maksimum besar file 3M
    $config['max_width']  = '5000'; //lebar maksimum 5000 px
    $config['max_height']  = '5000'; //tinggi maksimu 5000 px
    $config['file_name'] = $nmfile; //nama yang terupload nantinya

    $this->upload->initialize($config);

    if($_FILES['filefoto']['name'])
    {
        if ($this->upload->do_upload('filefoto'))
        {
            $gbr = $this->upload->data();
            $data = array(           
            'id_barang'         => $this->input->post('id_barang'),
            'nama_barang'       => $this->input->post('nama_barang'),
            'stock_barang'      => $this->input->post('stock_barang'),
            'harga_barang'      => $this->input->post('harga_barang'),
            'ukuran_barang'     => $this->input->post('ukuran_barang'),
            'gambar'            => $gbr['file_name']   
            );
            $this->barang_model->tambah_data($data); //akses model untuk menyimpan ke database

            //pesan yang muncul jika berhasil diupload pada session flashdata
            $this->session->set_flashdata("pesan", "<div class=\"col-md-12\"><div class=\"alert alert-success\" id=\"alert\">Insert data berhasil !!</div></div>");
            redirect('barang'); //jika berhasil maka akan ditampilkan view upload
        }else{
            //pesan yang muncul jika terdapat error dimasukkan pada session flashdata
            $this->session->set_flashdata("pesan", "<div class=\"col-md-12\"><div class=\"alert alert-danger\" id=\"alert\">Insert data gagal !!</div></div>");
            redirect('barang/tambah'); //jika gagal maka akan ditampilkan form upload
        }
    }

【问题讨论】:

    标签: php sql codeigniter


    【解决方案1】:
    $nmfile = "file".time().".png"; //nama file saya beri nama langsung dan diikuti fungsi time
    $config['upload_path'] = '/uploads/'; //path folder
    $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; //type yang dapat diakses bisa anda sesuaikan
    $config['max_size'] = '3072'; //maksimum besar file 3M
    $config['max_width']  = '5000'; //lebar maksimum 5000 px
    $config['max_height']  = '5000'; //tinggi maksimu 5000 px
    $config['file_name'] = $nmfile;
    
    $this->load->library('upload');
    
    if ($this->upload->do_upload())
        {
            $gbr = $this->upload->data();
            echo "<pre>";
            print_r($gbr);
            echo exit;
    

    然后检查上传目录。

    【讨论】:

    • 谢谢你,解决了我的问题!
    • 感谢您将答案标记为正确,请点赞。
    【解决方案2】:

    你可以使用 $this->upload->display_errors() 显示错误

    【讨论】:

      【解决方案3】:

      使用 $this->upload->display_errors()

      【讨论】:

        【解决方案4】:

        第一步 - 创建视图: 首先设置 Codeigniter base_url() 函数,然后转到 application>>views 文件夹。在 Codeigniter 3 的 views 文件夹中,你可以看到文件 - welcome_message.php,编辑这个文件并创建一个图片上传表单。您也可以复制并粘贴以下代码来创建图片上传表单。

        <html>
        <head>
          <title>Upload Image Form</title>
        </head>
        <body>
        <?php echo form_open_multipart('Welcome/image_upload/' , array('id' => 'img'));?>
          <h3>Image Upload Form</h3>
          <input type="file" name="pic" tabindex="2" required>
          <input type="text" name="alt" placeholder="Image Alt Text" tabindex="1" required>
          <button type="submit" id="img-submit" data-submit="Sending">Submit</button>
        </form>
        </body>
        </html>
        

        您还可以添加一些 CSS 代码来设计表单。

        第二步 - 创建数据库和图片上传文件夹: 现在在您的项目中创建一个文件夹,其中将上传图像并在您的项目数据库中从 phpmyadmin 创建一个表 - 'image_upload',您还可以复制并粘贴以下代码来创建一个表:

        CREATE TABLE `image_upload` (
        `image_url` VARCHAR( 50 ) NOT NULL ,
        `alt` VARCHAR( 50 ) NOT NULL 
        ) ENGINE = MYISAM ;
        

        第三步 - 控制器: 现在转到应用程序>>控制器,将有一个名为“Welcome.php”的 PHP 文件。首先,您需要添加表单和 URL 助手并加载数据库,如下所示:

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

        现在在你的控制器中创建一个图片上传功能,如下所示:

        function do_upload()
        {
          $url = "../images";
          $image=basename($_FILES['pic']['name']);
          $image=str_replace(' ','|',$image);
          $type = explode(".",$image);
          $type = $type[count($type)-1];
          if (in_array($type,array('jpg','jpeg','png','gif')))
          {
            $tmppath="images/".uniqid(rand()).".".$type; // uniqid(rand()) function generates unique random number.
            if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
            {
              move_uploaded_file($_FILES['pic']['tmp_name'],$tmppath);
              return $tmppath; // returns the url of uploaded image.
            }
          }
          else
          {
            redirect(base_url() . 'index.php/Welcome/not_img', 'refresh');// redirect to show file type not support message
          }
        }
        

        函数do_upload正在将welcome_message.php表格中选择的图片上传到您在第二步创建的文件夹中,并返回图片的URL。

        现在我们将上传图片的 URL 保存到 MySQL 数据库中。参见下面的代码:

        function image_upload()
        {
          $data ['image_url']= $this->do_upload();
          $data ['alt']= $this->input->post('alt');
          $this->db->insert('image_upload', $data);
          redirect(base_url() . 'index.php/Welcome/', 'refresh');// Redirect to Success page
        }
        

        image_upload函数会将图片的URL保存在你的数据库中。你可以使用下面的代码查看上传的图片:

        <?php
          $images = $this->db->get('image_upload')->result_array();
          foreach($images as $row):
        ?>
          <img src="<?php echo base_url().$row['image_url'];?>" class="img" alt="" />
        <?
          endforeach;
        ?>
        

        所以这些是使用 Codeigniter 3 上传图像并保存在 MySQL 数据库中的简单步骤。

        【讨论】:

          【解决方案5】:
          1. 首先在views目录中创建一个视图并添加一个表单。

            查看文件

            <!DOCTYPE html>
            
            <html>
            
             <head>
            
             <title>Codeigniter Upload Example</title>
            
              </head>
            
             <body>
            
            <?php echo $error; ?>
            
             <h3>Upload Example</h3>
            
             <?php echo form_open_multipart('upload/upload_file'); ?>
            
              <input type="file" name="userfile" size="20" />
            
               <br /><br />
            
               <input type="submit" value="upload" />
            
                 </form>
            
                </body>
            

          2. 创建文件夹用于存储上传的文件,例如(照片

          3. 接下来创建控制器,如下所示:

          上传控制器

           class Upload extends CI_Controller {
          
                  public function __construct()
                  {
                      parent::__construct();
                      $this->load->helper(array('form', 'url'));
                      $this->load->library('form_validation');
                  }
          
                  public function index()
                  {
                      $this->load->view('upload', array('error' => ' ' ));
                  }
          
                  public function upload_file()
                  {
                          $config['upload_path']          = './photos/';
                          $config['allowed_types']        = 'gif|jpg|png|pdf|doc';
                          $config['max_size']             = 100;
                          $config['max_width']            = 1024;
                          $config['max_height']           = 768;
          
                          $this->load->library('upload', $config);
          
                          if ( ! $this->upload->do_upload('userfile'))
                          {
          
                              $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
          
                              $error = array('error' => $this->upload->display_errors());
          
                              $this->load->view('upload', $error);
                          }
                          else
                          {
                              $data = array('upload_data' => $this->upload->data());
          
                              $this->load->view('someview', $data);
                          }
                  }
          }
          

          查看上传的文件信息。

          将图片上传到某个目录后,您可以创建另一个视图文件并分配上传的数据并可以使用文件信息。

          <?php foreach ($upload_data as $item => $value): ?>
          
          <p><?php echo $item;?>: <?php echo $value;?></p>
          
          <?php endforeach; ?>
          

          上传的文件

            <img src="<?php echo base_url().'/uploads/'.$upload_data['file_name']; ?>" />
          

          保存到数据库

          您可以使用以上图片信息和pass,图片名称,路径及相关信息给您查询

          希望此代码对您有所帮助。您可以在此处找到有关如何使用 codeigniter 上传文件的详细教程。 Codeigniter file upload example.

          【讨论】:

            猜你喜欢
            • 2012-04-22
            • 2011-05-29
            • 2011-06-14
            • 2018-04-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多