Start your mongo service, mongod --dbpath ~/mongodb_Data (replace ~/mongodb_Data with your own path)
Use mongofiles -d test put /Users/taozhi/Pictures/bg/21.jpg to add a picture to gridfs, and replace the image path /Users/taozhi/Pictures/bg/21.jpg with your own. After the addition is successful, you will get the following prompt:
2016-11-03T11:18:42.851+0800 connected to: localhost
added file: /Users/taozhi/Pictures/bg/21.jpg
mongoConnect to the default mongo server, db.fs.files.find()you can see the information of the image just stored, including file name, file size, block size, time and MD5 check code, etc.
The code was written a bit hastily, and there are many areas that can be optimized. You can improve it yourself. I just provide a reference for you. I hope it will be helpful to you
Show image in GridFS in front-end using express
mongo preparation
Start your mongo service,
mongod --dbpath ~/mongodb_Data
(replace ~/mongodb_Data with your own path)Use
mongofiles -d test put /Users/taozhi/Pictures/bg/21.jpg
to add a picture togridfs
, and replace the image path /Users/taozhi/Pictures/bg/21.jpg with your own. After the addition is successful, you will get the following prompt:mongo
Connect to the default mongo server,db.fs.files.find()
you can see the information of the image just stored, including file name, file size, block size, time and MD5 check code, etc.According to the _id of the file, query all the chunks in the fs.chunks collection,
db.fs.chunks.find({files_id:ObjectId('581aad5aa3205aa0b201aceb')})
The data preparation work is almost done here, let’s write the application service!
Or you can also use GridFS's writeFile directly. The detailed code can be seen below
node service
The service is divided into several steps
If it is a set of processes, read the file
Write to mongo
Read data during service
Return to frontend
Because what you requested is a picture, let me read the file data here, base64 encode it and return it to the front end, and you can see the picture
app.js
index.eje
Personal test was successful.
The code was written a bit hastily, and there are many areas that can be optimized. You can improve it yourself. I just provide a reference for you. I hope it will be helpful to you