Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save BLOB image to disk from database in PHP

Tags:

php

I have stored an image in my database as a BLOB file. This might not be the best practice (I know this). I wanted to create a link on my page when clicked with prompt the user with the typical save file prompt so they can save the file on their personal disk.

I have researched online but what I am trying does't not seem to work it just posts the bytes to my page and not in a file. My code to save the file is below. I am using a framework so the DB transaction and retrevial code might look strange but the values are being set properly. The files were also encoded in base64 before being stored in the DB so I call the decode function to return it to its normal state.

function save_file($file_id) {
    $result = $DB->get_file($file_id);   
    $size = $result->fields['size'];  //1024
    $mime = $result->fields['mime'];  //image/jpg
    $name = $result->fields['name'];  //test.jpg

    header("Content-Disposition:attachment;filename=".$name);
    header("Content-Type=: ".$mime);
    header("Content-Length: ".$size);

    base64_decode(file);
    echo($file);
    exit();
}
like image 985
FirstQuestion Avatar asked Dec 13 '22 21:12

FirstQuestion


2 Answers

I think your Content-Type header is wrong. That = seems like a typo.

like image 131
Jason McCreary Avatar answered Dec 29 '22 06:12

Jason McCreary


function save_file($file_id, $target_folder) {
    $result       = $DB->get_file($file_id);   
    $file_content = $result->fields['your_file_content_field'];
    $name         = $result->fields['name'];

    /* Decode only if the file contents base64 encoded 
     * before inserting to database.
     */
    $file_content = base64_decode($file_content);

    return file_put_contents($target_folder.'/'.$name, $file_content);
}
like image 36
Emre Yazici Avatar answered Dec 29 '22 07:12

Emre Yazici