簡體   English   中英

如何將圖像存儲在數據庫中

[英]how to store the images in the database

這是我的網站,由“ CodeIgniter”框架和我創建的數據庫組成

我的個人網站

如果您在首頁上單擊牆上的圖像,則將在此類別中輸入以查看所有圖像,您會看到某些圖像無法顯示,這是因為在創建數據庫時,我將所有圖像在我的facebook個人資料上,將每個圖像的url復制到數據庫中,然后用php和“ foreach”顯示它們,但是facebook會不時更改其url,這使得該URL不再鏈接到該圖像。

我已經嘗試過從我的Google驅動器中獲取圖片的url,這很糟糕,因此通過借用第三部分的url來存儲許多圖片(200多個)不是一種穩定的方法,有人可以告訴我這樣做的正確和穩定的方法?

非常感謝!

根據您的要求,最好將圖像存儲在文件系統中(更好的緩存(服務器和客戶端)|減少數據庫負載),並節省大量用戶帶寬(返回用戶),並將相應的文件路徑保存在文件系統中。數據庫。 但是您必須優雅地處理緩存。 請考慮使用Amazon Web Service S3存儲服務。

供進一步參考:這是Codeigniter文檔中的代碼片段。

問候,HBK

數據庫:

CREATE TABLE `app_files` (
  `file_id` int(10) NOT NULL AUTO_INCREMENT,
  `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `file_data` longblob NOT NULL,
  PRIMARY KEY (`file_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

保存圖像以建模:

if(!empty($_FILES["company_logo"]) && $_FILES["company_logo"]["error"] == UPLOAD_ERR_OK && !is_on_demo_host())
{
    $allowed_extensions = array('png', 'jpg', 'jpeg', 'gif');
    $extension = strtolower(pathinfo($_FILES["company_logo"]["name"], PATHINFO_EXTENSION));

    if (in_array($extension, $allowed_extensions))
    {
        $config['image_library'] = 'gd2';
        $config['source_image'] = $_FILES["company_logo"]["tmp_name"];
        $config['create_thumb'] = FALSE;
        $config['maintain_ratio'] = TRUE;
        $config['width']     = 170;
        $config['height']   = 60;
        $this->load->library('image_lib', $config); 
        $this->image_lib->resize();
        $company_logo = $this->Appfile->save($_FILES["company_logo"]["name"], file_get_contents($_FILES["company_logo"]["tmp_name"]), $this->config->item('company_logo'));
    }
}

模型:

<?php
class Appfile extends CI_Model 
{       
    function get($file_id)
    {
        $query = $this->db->get_where('app_files', array('file_id' => $file_id), 1);

        if($query->num_rows()==1)
        {
            return $query->row();
        }

        return "";

    }

    function save($file_name,$file_data, $file_id = false)
    {
        $file_data=array(
        'file_name'=>$file_name,
        'file_data'=>$file_data
        );

        if (!$file_id)
        {
            if ($this->db->insert('app_files',$file_data))
            {
                return $this->db->insert_id();
            }

            return false;
        }

        $this->db->where('file_id', $file_id);
        if ($this->db->update('app_files',$file_data))
        {
            return $file_id;
        }

        return false;
    }

    function delete($file_id)
    {
        return $this->db->delete('app_files', array('file_id' => $file_id)); 
    }
}

?>

查看圖像:

    $file = $this->Appfile->get($file_id);
    header("Content-type: ".get_mime_by_extension($file->file_name));
    echo $file->file_data;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM