0

I am trying to make a small program for uploading and displaying files from mongoDB and PHP Uploading of files is being done properly.

I have uploaded simple image files of 2-3MB to gridFS in mongoDB but my download code is giving Long array of bytes along with html code as output

I want to download file temporary to display it in browser. What changes should i do in this code

Code for Uploading File:

<?php
if(isset($_POST['formsubmit']))
{
    $m = new MongoClient();
    $coll = $m->test;
    $gridFS = $coll->getGridFS();
    $tag = $_POST['username'];
    $gridFS->storeUpload('pic',array("tag"=>$tag));
    echo 'File Uploaded Successfully';
    $m->close();
}
?>

<html>
<head><title>Upload Image</title></head>
<body>
    <form method="POST" enctype="multipart/form-data">
        <label for="username">Username:</label>
        <input type="text" name="username" id="username" />
        <label for="pic">Please upload a profile picture:</label>
        <input type="file" name="pic" id="pic" />
        <input type="submit" value="Register" name="formsubmit"/>
    </form>
</body>
</html>

Code for Downloading File:

<html>
    <head> Download Image</head>
    <body>
        <form method="POST" enctype="multipart/form-data">
            <label for="username">Username:</label>
            <input type="text" name="username" id="username" />
            <input type="submit" value="Register" name="formsubmit"/>
        </form>
    </body>
</html>

<?php
if (isset($_POST['formsubmit'])) {
    $m = new MongoClient();
    $coll = $m->test;
    $images = $coll->getGridFS();

    $image = $images->findOne(array(
        'tag' => $_POST['username'],
    ));

    header('Content-type: image/png;');
    echo $image->getBytes();
}
?>

Its Showing me following error if opened in browser

The image "localhost/PHP/Project_working/fileretrive.php" cannot be displayed because it contains errors.

theoneabhinav
  • 95
  • 1
  • 6
  • [`.getGridFS()`](http://php.net/manual/en/mongodb.getgridfs.php) is not a collection method. Also very bad practice to "connect" is each "page" like this. You should be using an application global or something else that can be shared. – Neil Lunn Sep 16 '14 at 09:16
  • ok. i will consider opening only one global collection.but i am collecting file back using getbytes(). – theoneabhinav Sep 16 '14 at 09:21
  • I'm trying to inform you that this is not the correct way to use GridFS methods with the driver. All you are doing is using standard collection methods. This does not "automatically" get data from all possible "chunks" and either store or re-construct properly. See the [documentation](http://php.net/manual/en/class.mongogridfs.php) – Neil Lunn Sep 16 '14 at 09:25

0 Answers0