How to display an Image from a mysql blob

前端 未结 4 2085
臣服心动
臣服心动 2020-12-12 04:23

I am trying to display an image from a MySQL blob field. I have tried a few different things and none of them seem to work.

I have tried:

  • hea

4条回答
  •  无人及你
    2020-12-12 05:10

    Another option you might consider (assuming you are on Apache):

    Create an .htaccess file with a mod_rewrite for all image extensions (png, jpg, gif).

    Have it redirect to a php script that looks up the image requested in the DB. If it is there, it echos out the header and BLOG. If it isn't there, it returns a standard 404.

    This way you can have:

    
    

    Which then gets redirected ala:

    RewriteEngine on
    RewriteRule \.(gif|jpg|png)$ imagelookup.php
    

    This script does a query for the image, which (obviously) assumes that the requested image has a unique key that matches the filename in the URL:

     $url = $_SERVER['REQUEST_URI'];
     $url_parts = explode("/", $url);
     $image_name = array_pop($url_parts);
    

    Now you have just the image filename. Do the query (which I shall leave up to you, along with any validation methods and checks for real files at the address, etc.).

    If it comes up with results:

     header('Content-type: image/jpeg');
     header('Content-Disposition: inline; filename="adorablepuppy.jpg"');
     print($image_blog);
    

    otherwise:

     header("HTTP/1.0 404 Not Found");
    

    FYI: I have no idea if this would be bad in terms of performance. But it would allow you to do what I think you want, which is output the image as though it were a flat image file on the server using a simple image element. I'm inclined to agree that BLOBs are not the best way to go, but this does avoid any cross-browser issues.

提交回复
热议问题