Chani
Chani

Reputation: 5165

Store images in a MongoDB database

How can I store images in a MongoDB database rather than just text? Can I create an array of images in a MongoDB database? Will it be possible to do the same for videos?

Upvotes: 224

Views: 448629

Answers (9)

Muhammad Adeel
Muhammad Adeel

Reputation: 1

  1. Storing Image as a Base64 String Convert the selected image into a Base64 string and store it as a string in MongoDB.

Pros: Simple and avoids dealing with file storage.

Cons: Increases database size significantly because Base64 encoding adds ~33% overhead.

Example:

const image = await ImagePicker.launchImageLibraryAsync({ base64: true });
const base64Image = image.base64;

// Save to MongoDB
const imageDocument = { image: base64Image };
await db.collection('images').insertOne(imageDocument);

Upvotes: 0

Tharindu
Tharindu

Reputation: 650

You can use the bin data type if you are using any scripting language to store files/images in MongoDB. Bin data is developed to store small size of files.

Refer to your scripting language driver. For PHP, click here.

Upvotes: 10

NeNaD
NeNaD

Reputation: 20304

Can you store files in MongoDB?

Yes.

Should you store files in MongoDB?

No.


MongoDB is NOT a good place for storing files. If you want to store files, you should use storages like Amazon S3 or Google Could Storage.

The good practice is to store the files in a storage and then to just save the URI of the uploaded image in the MongoDB.

Upvotes: 10

Samkit Shah
Samkit Shah

Reputation: 268

install below libraries

var express = require(‘express’);
var fs = require(‘fs’);
var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;
var multer = require('multer');

connect ur mongo db :

mongoose.connect(‘url_here’);

Define database Schema

var Item = new ItemSchema({ 
    img: { 
       data: Buffer, 
       contentType: String 
    }
 }
);
var Item = mongoose.model('Clothes',ItemSchema);

using the middleware Multer to upload the photo on the server side.

app.use(multer({ dest: ‘./uploads/’,
  rename: function (fieldname, filename) {
    return filename;
  },
}));

post req to our db

app.post(‘/api/photo’,function(req,res){
  var newItem = new Item();
  newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
  newItem.img.contentType = ‘image/png’;
  newItem.save();
});

Upvotes: 14

AshvinG
AshvinG

Reputation: 66

var upload = multer({dest: "./uploads"});
var mongo = require('mongodb');
var Grid = require("gridfs-stream");
Grid.mongo = mongo;

router.post('/:id', upload.array('photos', 200), function(req, res, next){
gfs = Grid(db);
var ss = req.files;
   for(var j=0; j<ss.length; j++){
     var originalName = ss[j].originalname;
     var filename = ss[j].filename;
     var writestream = gfs.createWriteStream({
         filename: originalName
     });
    fs.createReadStream("./uploads/" + filename).pipe(writestream);
   }
});

In your view:

<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="photos">

With this code you can add single as well as multiple images in MongoDB.

Upvotes: 4

victoriza
victoriza

Reputation: 436

You can try this one:

String newFileName = "my-image";
File imageFile = new File("/users/victor/images/image.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();

Upvotes: 28

Mike Causer
Mike Causer

Reputation: 8314

"You should always use GridFS for storing files larger than 16MB" - When should I use GridFS?

MongoDB BSON documents are capped at 16 MB. So if the total size of your array of files is less than that, you may store them directly in your document using the BinData data type.

Videos, images, PDFs, spreadsheets, etc. - it doesn't matter, they are all treated the same. It's up to your application to return an appropriate content type header to display them.

Check out the GridFS documentation for more details.

Upvotes: 80

Mick Cullen
Mick Cullen

Reputation: 9454

http://blog.mongodb.org/post/183689081/storing-large-objects-and-files-in-mongodb

There is a Mongoose plugin available on NPM called mongoose-file. It lets you add a file field to a Mongoose Schema for file upload. I have never used it but it might prove useful. If the images are very small you could Base64 encode them and save the string to the database.

Storing some small (under 1MB) files with MongoDB in NodeJS WITHOUT GridFS

Upvotes: 14

Gates VP
Gates VP

Reputation: 45277

Please see the GridFS docs for details on storing such binary data.

Support for your specific language should be linked to at the bottom of the screen.

Upvotes: 135

Related Questions