1.フロントエンドアップロードファイルhtml index.html
<!DOCTYPE html PUBLIC "-// W3C // DTD XHTML 1.0 Transitional // EN" "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 </タイトル> </ head> <body> <form action = "upload.php" method = "post" enctype = "multipart / form-data"> <label for = "upfile">上传图片</ label> <入力タイプ= "file" id = "upfile" name = "upfile" /> <input type = "submit" /> </ form> </ body> </ html>
2.ファイルをMongoDBデータベースにアップロードし、画像upload.phpのインデックスIDを返します。
<?php //画像を ヘッダーにアップロード( "Content-type:text / html; charset = utf-8"); // Mongoに接続してGFSを初期化 // picDBという名前のデータベース; pic_useridという名前のコレクション $ conn = new MongoClient() ; $ db = $ conn-> picDB; // gridfsオブジェクトを取得 $ prefix = 'pic'; $ collection = $ db-> getGridFS($ prefix); //画像をアップロード する(isset($ _ FILES ['upfile'] )){ $ id = $ collection-> storeUpload( 'upfile'); $ id = strval($ id); echo "<p>画像パスは次のとおりです:<font color = red> http:// {$ _SERVER [' HTTP_HOST ']} / image.php?Id = {$ id} </ font> </ p> "; } ?>
3.画像IDに従って、MongoDBから直接画像リソースを取得し、image.phpを表示します。
<?php // IDインデックス値、つまり画像のバイナリデータに従って画像リソースを取得 $ conn = new Mongo(); $ db = $ conn-> picDB; // gridfsオブジェクトを取得 $ prefix = 'pic'; $コレクション= $ db-> getGridFS($ prefix); $ id = $ _GET ['id']; $ object = $ collection-> findOne(array( '_ id' => new MongoId($ id))); header( 'コンテンツタイプ:image / jpg '); echo $ object-> getBytes(); ?>