PHP operation MongoDB GridFS storage file

1. The front-end upload file 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</title>

</head>


<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    <label for="upfile" >上传图片</label>
    <input type="file" id="upfile" name="upfile" />
    <input type="submit" />
</form>

</body>

</html>

 

2. Upload the file into the MongoDB database and return the index ID of the picture upload.php

 

<? php 
// Upload picture to 
header ("Content-type: text / html; charset = utf-8"); 
// Connect to Mongo and initialize GFS 
// Database named picDB; Collection named pic_userid 
$ conn = new MongoClient () ; 
$ db = $ conn-> picDB; 
// Get gridfs object 
$ prefix = 'pic'; 
$ collection = $ db-> getGridFS ($ prefix); 

// Upload picture 
if (isset ($ _ FILES ['upfile'] )) { 
    $ id = $ collection-> storeUpload ('upfile'); 
    $ id = strval ($ id); 
    echo "<p> The image path is: <font color = red> http: // {$ _SERVER [' HTTP_HOST ']} / image.php? Id = {$ id} </ font> </ p> "; 
} 
?>

 

3.According to the image ID, get the image resource directly from MongoDB and display image.php

 

<? php 
// According to the ID index value, the image resource is taken out, that is, the image binary data 
$ conn = new Mongo (); 
$ db = $ conn-> picDB; 
// Get the gridfs object 
$ prefix = 'pic'; 
$ collection = $ db-> getGridFS ($ prefix); 

$ id = $ _GET ['id']; 

$ object = $ collection-> findOne (array ('_ id' => new MongoId ($ id))); 
header (' Content-type: image / jpg '); 
echo $ object-> getBytes (); 

?>
Published 210 original articles · praised 37 · 170,000 views +

Guess you like

Origin blog.csdn.net/u012757419/article/details/104063524