PHP implementation Gridfs storage files to MongoDB tutorial

Source: Internet
Author: User
Tags mongodb mongodb tutorial


Generally take the first method, directly transfer files, the second method suitable for the generation of data not saved to the local upload but directly to the binary system to MongoDB, the third way is to directly upload the form of the file into the MongoDB.


Initialize Gridfs
$conn = new Mongo (); Connect MongoDB
$db = $conn->photos; Select Database
$grid = $db->getgridfs (); Get Gridfs Object

Gridfs has three ways of storing files
The first type of direct storage file
$id = $grid->storefile ("./logo.png");

Second storage file binary stream
$data = Get_file_contents ("./logo.png");
$id = $grid->storebytes ($data, Array ("Parame" => ' additional parameters will be deposited with the picture '));

The third type of file to save direct form submissions $_files
$id = $grid->storeupload (' upfile ');
Equivalent
$id = $grid->storefile ($_files[' upfile '] [' tmp_name ']);

--------------above is to save the picture--start reading the picture below----------------

Returns $ID = MD5 string after successful save
$logo = $grid->findone (Array (' _id ' => $id)); Take _id as index to get files
Header (' content-type:image/png '); Output Picture Header
echo $logo->getbytes (); Output data stream

This feeling is the file stream form saved to the database, let small set feel that is the picture file saved to the database the same truth.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.