【问题标题】:Saving image in the database not working properly将图像保存在数据库中无法正常工作
【发布时间】:2013-11-14 14:32:32
【问题描述】:

我正在尝试创建一个跨平台应用程序,我想使用 Codeigiter 将来自不同设备的图像保存在数据库中。我可以从设备中选择图像,但我对如何保存图像并从数据库中检索图像感到困惑和储备。

控制器

function addstatesoothing() {

    // write user data into the user database
    $config['upload_path'] = './';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '1000000';
    $config['overwrite'] = TRUE;
    $config['remove_spaces'] = TRUE;
    $config['encrypt_name'] = FALSE;

    $this->load->library('upload', $config);
    $image_path = $this->upload->data('soothing-img');
    $data = array(
        'soothing-img' => $image_path[full_path],
        'soothing-title' => $this->input->post('soothing-title'),
    );
    $this->favourite_db->addstatesoothing($data);
    $this->load->view('soothing');
}

型号

function addstatesoothing($data) {
    $this->load->database();
    $this->db->insert('soothing', $data);
    return $data;
}

查看

 <form method="post" action="addstatesoothing">
                <!--  <button data-theme="d" onclick="capturePhoto();">Capture Photo</button> -->
                <a data-theme="d" onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Click to Add Pictures</a> 
                <img style="width:100%;" id="largeImage" src="" name="soothing-img"/> <br>
                <input type="text" name="soothing-title" id="Climbed a Mountain" value="" placeholder="Climbed a Mountain"/>
                <button data-theme="a">Save Memory</button>
                </form>

【问题讨论】:

  • 迷茫和囤货不是这里能解决的问题,那你的编程问题是什么?
  • 以上代码没有将图片文件保存到数据库中
  • 啊,我以为 `$this->db->insert('soothing', $data);` 会这样做,但有人已经为你做了功课 ;-)

标签: php mysql codeigniter cross-browser


【解决方案1】:

将图像保存在数据库中:

1 - 您在数据库中的图像字段应该是 BLOB 类型。

2 - 从图像中获取文件内容:

$image = file_get_contents($_FILES['image']['tmp_name']);

3 - 将其保存在数据库的 BLOB 类型字段中

mysql_query("insert into images (image) values ('$image') ");

我不知道您是否使用另一种方法将数据保存在数据库中,您的代码有点不同,但就是这样,对吧?最后会在数据库中插入一行,如果您有任何疑问,请在此处发表评论,但此时一切都很容易,ham?现在让我们去检索图像

首先,将图像内容存储在数据库中是一个真正的错误,但这不是问题,对吧?所以我不是这种方法的专家,但我会这样做:

创建另一个页面,如 image.php,通过参数接收一些 id 或图像名称

image.php:

<?php

$id = $_GET['id']; 
$query = "SELECT image FROM images WHERE `id`=$id";
$result = mysql_query($query);

header("Content-type: image/jpeg"); //if is another format like .png change here


while($row = mysql_fetch_assoc($result))
{
    echo $row['image'];
}
?>

很好,你有一个很好的 *.php 文件,它可以像任何 *.jpg 文件一样响应图像,所以现在在你的 HTML 中调用它

SomePage.html

<img src="image.php?id=12345" />

好的,全部完成,

但是为什么我说保存图像内容不好?: 伙计们太棒了,我们有惊人的材料来解释为什么将图像保存在数据库中是不好的!你可以检查一下,这里是:

  1. Storing Images in DB - Yea or Nay?
  2. Store images in database or on file system

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多