1. El archivo de carga front-end html index.html
<! DOCTYPE html PUBLIC "- // W3C // DTD XHTML 1.0 Transitional // ES" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http : //www.w3.org/1999/xhtml "> <head> <meta http-equiv =" Content-Type "content =" text / html; charset = utf-8 "/> <title> Mongo Gridfs </ title> </head> <body> <form action = "upload.php" method = "post" enctype = "multipart / form-data"> <label for = "upfile"> 上传 图片 </label> <tipo de entrada = "file" id = "upfile" name = "upfile" /> <input type = "submit" /> </form> </body> </html>
2. Cargue el archivo en la base de datos MongoDB y devuelva el ID de índice de la imagen upload.php
<? php // Cargar imagen al encabezado ("Content-type: text / html; charset = utf-8"); // Conéctese a Mongo e inicialice GFS // Base de datos llamada picDB; Colección llamada pic_userid $ conn = new MongoClient () ; $ db = $ conn-> picDB; // Obtener el objeto gridfs $ prefix = 'pic'; $ colección = $ db-> getGridFS ($ prefix); // Cargar imagen if (isset ($ _ FILES ['upfile'] )) { $ id = $ colección-> storeUpload ('upfile'); $ id = strval ($ id); echo "<p> La ruta de la imagen es: <font color = red> http: // {$ _SERVER [' HTTP_HOST ']} / image.php? Id = {$ id} </ font> </ p> "; } ?>
3. Según la ID de la imagen, obtenga el recurso de imagen directamente de MongoDB y muestre image.php
<? php // Según el valor del índice de ID, se saca el recurso de imagen, es decir, los datos binarios de la imagen $ conn = new Mongo (); $ db = $ conn-> picDB; // Obtener el objeto gridfs $ prefix = 'pic'; $ colección = $ db-> getGridFS ($ prefijo); $ id = $ _GET ['id']; $ object = $ collection-> findOne (array ('_ id' => new MongoId ($ id))); header (' Tipo de contenido: image / jpg '); echo $ object-> getBytes (); ?>