PHP operation MongoDB Gridfs store files, such as picture files

Source: Internet
Author: User
Tags connect mongo dsn findone html form save file

Gridfs is a built-in feature of MongoDB that provides a set of file manipulation APIs to utilize MongoDB to store files, the basic principle of Gridfs is to save files in two collection, a save file index, a save file content, The contents of the file are divided into blocks of a certain size, and each piece exists in a document, which not only provides the file storage, but also provides the storage of some additional properties related to the file (such as MD5 value, file name, etc.).

01

<?php

02

Initialize Gridfs

03

$conn = new Mongo (); Connect to MongoDB

04

$db = $conn->photos; Select Database

05

$collection = $db->getgridfs (); Get Gridfs Object

06

07

Gridfs There are three ways to store files

08

The First Direct storage file

09

$id = $collection->storefile ("./logo.png");

10

11

Second binary stream for storage of files

12

$data = Get_file_contents ("./logo.png");

13

$id = $collection->storebytes ($data, Array ("param" + + ' additional parameters will be saved with the image));

14

15

The third file to save direct form submissions $_files

16

$id = $collection->storeupload (' upfile ');

17

Equivalent

18

$id = $collection->storefile ($_files[' upfile ' [' tmp_name ']);

19

20

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

21st

22

return $id = MD5 string after successful save

23

$logo = $collection->findone (Array (' _id ' = $id)); Get the file with the _id index

24

Header (' content-type:image/png '); Output Image Header

25

echo $logo->getbytes (); Output data stream

26

?>

Special remark:

by $id = $collection->storefile ($_files[' upfile ' [' tmp_name ']); The generated ID is the ID object of MongoDB, not a string! As in the following format:

1

{

2

"_id": ObjectId ("525418525ba8a18c1b000001"),

3

"FileName": "D:\\php\\xampp\\tmp\\php8116.tmp",

4

"Uploaddate": Isodate ("2013-10-08t14:36:02.0z"),

5

"Length": Numberint (55862),

6

"ChunkSize": Numberint (262144),

7

"MD5": "A6f19f3434f0b36bb2611cd4c6d82b35"

8

}

However, we can use the $id = Strval ($id), the above ID object string, if the above 525418525ba8a18c1b000001 value can be obtained, and then stored in the MySQL database, then the string ID can be used as a condition, Locate the appropriate MongoDB resource. The reference code is as follows:

1

$conn = new Mongo (C (' 127.0.0.1:27017 ')); If you set a password, configure the DSN yourself

2

$db = $conn->selectdb (' Edu_sns '); Select Database

3

$collection = $db->getgridfs (' Zk_attach '); Select a collection, equal to the selection data table

4

5

$id =$_get[' id '];

6

$object = $collection->findone (Array (' _id ' =>new MongoId ($id)));

7

Header (' content-type:image/png ');

8

echo $object->getbytes ();

Recently, due to work needs to study the next Gridfs, and compiled a demo out. Share your experience.

gfs.php file

01

<?php

02

Connect MONGO and Initialize GFs

03

$conn = new Mongo (C (' 127.0.0.1:27017 ')); If you set a password, configure the DSN yourself

04

$db = $conn->selectdb (' Edu_sns '); Select Database

05

$collection = $db->getgridfs (' Zk_attach '); Select a collection, equal to the selection data table

06

07

Upload image

08

if (Isset ($_files[' upfile ')) {

09

10

Save the newly uploaded file

11

$size = $_files[' upfile ' [' Size '];

12

$MD 5 = md5_file ($_files[' upfile ' [' tmp_name ']);

13

$exists = $collection->findone (Array (' MD5 ' = + $md 5, ' length ' = = $size), array (' MD5 '));

14

if (empty ($exists)) {

15

$collection->storeupload (' upfile ');

16

17

or modify it to the following code and deposit some custom parameters

18

/*

19

$filename =$_files[' upfile ' [' name '];

20

$filetype =$_files[' upfile ' [' type '];

21st

$tmpfilepath =$_files[' upfile ' [' tmp_name '];

22

$id = $gridfs->storefile ($tmpfilepath, Array (' filename ' = = $filename, ' filetype ' = + $filetype));

23

*/

24

25

} else {

26

Unlink ($_files[' upfile ' [' tmp_name ']);

27

}

28

echo "<p> picture path: <font color=red>http://{$_server[' http_host ']}{$_server[' Request_uri ']}?img={$md 5} </font></p> ";

29

30

} elseif ($id = $_get[' img ') {//Generate picture

31

32

Index picture file

33

$image = $collection->findone (Array (' MD5 ' = $id));

34

35

Set document type, display picture

36

$img _bytes = $image->getbytes ();

37

Include_once ' thumb.php ';

38

$w = Is_numeric ($_get[' W ')? Intval ($_get[' W ']): 100;

39

Thumb::maxwidth ($img _bytes, $w);

40

41

} elseif ($id = $_get[' del ') {//delete picture

42

$s = $collection->remove (Array (' MD5 ' = $id));

43

Header (' Location: '. $_server[' Http_referer ');

44

45

} else {//Picture List

46

$cursor = $collection->find ();

47

foreach ($cursor as $obj):

48

Echo ' <p><a href= '? img= '. $obj->file[' MD5 '). ' &w=800 ' >file[' MD5 '). ' "border=" 0 "/></a><a href="? del= '. $obj->file[' MD5 '). ' > Delete </a></p> ';

49

Endforeach

50

;

51

}

52

?>

thumb.php thumbnail files

001

<?php

002

Class Thumb {

003

004

/**

005

* Scale images at maximum width

10W

*

007

* @param string $im image metadata

008

* @param float $w Maximum width

009

*/

010

static function MaxWidth ($im, $w) {

11P

if (Empty ($im) | | empty ($w) | |!is_numeric ($W)) {

012

throw new Exception ("Missing required parameters");

013

}

014

$im = imagecreatefromstring ($im); Create an image

015

List ($im _w, $im _h) = Self::getsize ($im); Get Image Width Height

11W

if ($im _w > $w) {

017

$new _w = $w;

018

$new _h = $w/$im _w * $im _h;

019

} else {

020

$new _w = $im _w;

021

$new _h = $im _h;

022

}

023

$DST _im = Imagecreatetruecolor ($new _w, $new _h);

024

Imagecopyresampled ($dst _im, $im, 0, 0, 0, 0, $new _w, $new _h, $im _w, $im _h);

025

Header (' Content-type:image/jpeg ');

026

Imagepng ($dst _im);

12V

Imagedestroy ($dst _im);

028

Imagedestroy ($im);

029

}

030

031

/**

032

* Scale images at maximum height

033

*

034

* @param string $im image metadata

035

* @param float $w Maximum height

036

*/

037

static function MaxHeight ($im, $h) {

038

if (Empty ($im) | | empty ($h) | |!is_numeric ($H)) {

039

throw new Exception ("Missing required parameters");

040

}

041

$im = imagecreatefromstring ($im); Create an image

042

List ($im _w, $im _h) = Self::getsize ($im); Get Image Width Height

043

if ($im _h > $h) {

044

$new _w = $h/$im _h * $im _w;

045

$new _h = $h;

046

} else {

047

$new _w = $im _w;

048

$new _h = $im _h;

049

}

050

$DST _im = Imagecreatetruecolor ($new _w, $new _h);

051

Imagecopyresampled ($dst _im, $im, 0, 0, 0, 0, $new _w, $new _h, $im _w, $im _h);

052

Header (' Content-type:image/jpeg ');

053

Imagepng ($dst _im);

054

Imagedestroy ($dst _im);

055

Imagedestroy ($im);

15W

}

057

058

/**

059

* Generate fixed-size images and scale them proportionally

060

*

16P

* @param string $im image metadata

062

* @param float $w Maximum width

063

* @param float $h Maximum height

064

*/

16T

static function fixed ($im, $w, $h) {

066

if (Empty ($im) | | empty ($w) | | | empty ($h) | |!is_numeric ($w) | |!is_numeric ($H)) {

067

throw new Exception ("Missing required parameters");

068

}

069

$im = imagecreatefromstring ($im); Create an image

070

List ($im _w, $im _h) = Self::getsize ($im); Get Image Width Height

071

if ($im _w > $im _h | | $w < $h) {

072

$new _h = intval ($w/$im _w) * $im _h);

073

$new _w = $w;

074

} else {

075

$new _h = $h;

076

$new _w = intval ($h/$im _h) * $im _w);

077

}

078

echo "$im _w x $im _h <br/> $new _w x $new _h <br/> $x $y"; exit;

079

Start creating a scaled image

080

$DST _im = Imagecreatetruecolor ($new _w, $new _h);

081

Imagecopyresampled ($dst _im, $im, 0, 0, 0, 0, $new _w, $new _h, $im _w, $im _h);

082

Header (' Content-type:image/jpeg ');

083

Imagepng ($dst _im);

084

Imagedestroy ($dst _im);

085

Imagedestroy ($im);

18W

}

087

088

/*

089

* Get image size

090

*

19P

* @param string $im image metadata

092

* @return Array

093

*/

094

protected static function GetSize ($im) {

095

Return Array (

096

Imagesx ($im),

19V

Imagesy ($im)

098

);

099

}

100

}

101

?>

index.html HTML form Files

01

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

02

03

04

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>

05

<title>mongo gridfs</title>

06

07

08

<body>

09

<form action= "gfs.php" method= "post" enctype= "Multipart/form-data" >

10

<input type= "File" name= "Upfile"/>

11

<input type= "Submit" value= "Upload"/> <a href= "gfs.php" > View pictures </a>

12

</form>

13

</body>

14


PHP operation MongoDB Gridfs storage file, tablet file

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.