简体   繁体   中英

Image corrupted while importing images from disk to MySQL Database

First of all, thanks for having a look at this. Allow me to explain:

I have images on disk that I'd like to place into the database in a longblob field. I've read that this is generally discouraged, but this is still something that is required in my application.

To import the images, I have the following code in my class:

$file_handle = fopen("$folder_path/$image","rb");
$file_content = fread($file_handle,filesize("$folder_path/$image"));

$image_record["file_name"] = $image;
$image_record["file_folder_id"] = $folder_data["folder_id"];
$image_record["file_owner_id"] = $this->current_user_data["user_id"];
$image_record["file_mime_type"] = mime_content_type("$folder_path/$image");
$image_record["file_binary"] = addslashes($file_content);

if($this->db_insert("file", $image_record))
{

    $this->view_file($this->load_file($image));
    echo header("Content-type:".$image_record["folder_type"]);
    $this->view_file($this->load_file($image));
    echo stripslashes($image_record["folder_binary"]);
}

It appears that when I try to save the binary to the database, the image data is getting corrupted by that process.

Using the same exact code, the $db->insert() statement works just fine on another website with near identical database schema except for the fact on the one it works, the storage engine is InnoDB instead of MyISAM.

The code within the if statement always displays an image, so I have my doubts about the data corruption happening at the time I read the file or display it.

Please help me understand what's going on.

Thanks!

You should base64 encode the images and store them in a longtext field, at leasts that is what i do and i find that it works great. Also, when grabbing the base64 records from your db, you can ectually echo out the base64 string into the images src property... here is the documentation: http://php.net/manual/en/function.base64-encode.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM