开发者

save BLOB image to disk from database in 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开发者_StackOverflow社区=".$name);
    header("Content-Type=: ".$mime);
    header("Content-Length: ".$size);

    base64_decode(file);
    echo($file);
    exit();
}


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


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜