Forked from aheckmann/storeImgInMongoWithMongoose.js
Created
December 5, 2013 22:07
-
-
Save freidamachoi/7814880 to your computer and use it in GitHub Desktop.
Image Upload - MEAN
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Module dependencies | |
*/ | |
var express = require('express'); | |
var fs = require('fs'); | |
var mongoose = require('mongoose'); | |
var Schema = mongoose.Schema; | |
// img path | |
var imgPath = '/path/to/some/img.png'; | |
// connect to mongo | |
mongoose.connect('localhost', 'testing_storeImg'); | |
// example schema | |
var schema = new Schema({ | |
img: { data: Buffer, contentType: String } | |
}); | |
// our model | |
var A = mongoose.model('A', schema); | |
mongoose.connection.on('open', function () { | |
console.error('mongo is open'); | |
// empty the collection | |
A.remove(function (err) { | |
if (err) throw err; | |
console.error('removed old docs'); | |
// store an img in binary in mongo | |
var a = new A; | |
a.img.data = fs.readFileSync(imgPath); | |
a.img.contentType = 'image/png'; | |
a.save(function (err, a) { | |
if (err) throw err; | |
console.error('saved img to mongo'); | |
// start a demo server | |
var server = express.createServer(); | |
server.get('/', function (req, res, next) { | |
A.findById(a, function (err, doc) { | |
if (err) return next(err); | |
res.contentType(doc.img.contentType); | |
res.send(doc.img.data); | |
}); | |
}); | |
server.on('close', function () { | |
console.error('dropping db'); | |
mongoose.connection.db.dropDatabase(function () { | |
console.error('closing db connection'); | |
mongoose.connection.close(); | |
}); | |
}); | |
server.listen(3333, function (err) { | |
var address = server.address(); | |
console.error('server listening on http://%s:%d', address.address, address.port); | |
console.error('press CTRL+C to exit'); | |
}); | |
process.on('SIGINT', function () { | |
server.close(); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi im new in mongoose so i have a basic questions i already save some image with your code but how can i display the image in ejs view
my code:
what im doing wrong? it displays just the box of the image