0

How can I store photos in mongodb and display it in my template Dynamically .

I have already created a form which stores the data of the user but I want to fetch the photo and render it through the template . Is there any way to do that ?

MongoDB only showing me C:\fakepath\33783991_259829344578817_7526307875543580672_n.jpg" ! What does that mean ? Is there any working package for meteor file except cloudinary ?

Hard Success
  • 11
  • 1
  • 2

4 Answers4

1

If you don't mind using a package use this one Meteor-Files

It's very easy this is an example below according to the documentation:

Upload form (template):

  <template name="uploadForm">
  {{#with currentUpload}}
    Uploading <b>{{file.name}}</b>:
    <span id="progress">{{progress.get}}%</span>
  {{else}}
    <input id="fileInput" type="file" />
  {{/with}}
</template>

Shared code:

import { FilesCollection } from 'meteor/ostrio:files';
const Images = new FilesCollection({collectionName: 'Images'});
export default Images; // To be imported in other files

Client's code:

import { Template }    from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
Template.uploadForm.onCreated(function () {
  this.currentUpload = new ReactiveVar(false);
});

Template.uploadForm.helpers({
  currentUpload() {
    return Template.instance().currentUpload.get();
  }
});

Template.uploadForm.events({
  'change #fileInput'(e, template) {
    if (e.currentTarget.files && e.currentTarget.files[0]) {
      // We upload only one file, in case
      // multiple files were selected
      const upload = Images.insert({
        file: e.currentTarget.files[0],
        streams: 'dynamic',
        chunkSize: 'dynamic'
      }, false);

      upload.on('start', function () {
        template.currentUpload.set(this);
      });

      upload.on('end', function (error, fileObj) {
        if (error) {
          alert('Error during upload: ' + error);
        } else {
          alert('File "' + fileObj.name + '" successfully uploaded');
        }
        template.currentUpload.set(false);
      });

      upload.start();
    }
  }
});

By default if config.storagePath isn't passed into Constructor it equals to assets/app/uploads and relative to a running script

On development stage: yourDevAppDir/.meteor/local/build/programs/server. Note: All files will be removed as soon as your application rebuilds or you run meteor reset. To keep your storage persistent during development use an absolute path outside of your project folder, e.g. /data directory.

On production: yourProdAppDir/programs/server. Note: If using MeteorUp (MUP), Docker volumes must to be added to mup.json, see MUP usage

Hint: You may then use the upload by base64 settings in the insert method and listen on the onuploaded event to save in your database.

To show the image in your template you may code it like so

<img src="data:image/jpeg;base64,{{ImginBase64}}" class="img-responsive"> 

Read more about Data URI Scheme

Source : Documentation

electrode
  • 473
  • 6
  • 13
0

You should encode your image in base64, in order to save it in a mongodb document.

Beware to not exceed the 16MB BSON format limit (or use Mongodb's GridFS). In the template you can use the base64 string of the image in the src attribute of the img.

Nuno Sousa
  • 832
  • 7
  • 15
0

It is better to use an Object storage service like GridFS, S3 or Google Cloud storage, and link it with your Mongo document. Alternatively, you can store your images in base64 format inside the Document itself.

https://forums.meteor.com/t/meteor-secure-file-upload-download-with-s3/38197

Hammad
  • 43
  • 8
  • No actually I am working locally . So Is there any way – Hard Success Dec 21 '18 at 06:20
  • "CollectionFS keeps a mongo collection that essentially points to images that have been stored in a file system somewhere, either on the disk or in the cloud. Afaik, you can't simply point CollectionFS at a directory full of files, you need to put the files there using CollectionFS in the first place." https://stackoverflow.com/questions/32424933/meteor-access-and-display-images – Hammad Dec 21 '18 at 06:39
0

There are lot of packages that you can use for this. I recommend CollectionFS .


You need to add this 3 packages and you're all set .

cfs:standard-packages cfs:gridfs // storage adapter package . You can change this if you want. cfs:filesystem

Let's start with Inserting Image.

1. Create ImageCollection.js in your lib folder

import { Mongo } from 'meteor/mongo';
export const BOOK = new Mongo.Collection('books');

var imageStore = new FS.Store.GridFS("images");

export const Images = new FS.Collection("images", {
    stores: [imageStore]
});Images.deny({
    insert: function(){
        return false;
    },
    update: function(){
        return false;
    },
    remove: function(){
        return false;
    },
    download: function(){
        return false;
    }
});
Images.allow({
    insert: function(){
        return true;
    },
    update: function(){
        return true;
    },
    remove: function(){
        return true;
    },
    download: function(){
        return true;
    }
})

2. Import Images collection in Client and Server side. For eg,

import {Images} from '../lib/imageCollection';

3. Add Input type "file" in form and according to your Use.

4. Create a change event in .JS file of that template.

'change #bookCover': function (event) {
        event.preventDefault();
        console.log("changed!")

        var files = event.target.files;
        for (var i = 0, ln = files.length; i < ln; i++) {
            Images.insert(files[i], function (err, fileObj) {

                // Inserted new doc with ID fileObj._id, and kicked off the data upload using HTTP
                bookImgId=fileObj._id;
            });
        }
    },

Check in Your Database Image will be inserted.

5. To Display Image Add this HTML where you want to see Image.

6. Add This code in Your js file where you are displaying image.

   bookImage: function (id) {
        // console.log(id);
        var imageBook = Images.findOne({_id:id});
        // console.log("img: "+imageBook);
        var imageUrl = imageBook.url();
        return imageUrl; // Where Images is an FS.Collection instance
    }

Note : Make sure you're importing your Book collection where you want display Image.

Shaiv
  • 41
  • 2