Simple code for storing images coming from the frontend to Node.js using Mongoose?


Image result for express-fileupload

Image is not stored in database. Only the path of the image is stored in database.
For example -
You write a code to image video then -
On uploading image it will get stored on desired server/folder.
Now you can fetch your image by simply writing code -
  1. <img src = "fetch_path_from_database_in_desired_language" />
So, src will give the path of folder which you have stored in database.
This is only back-end code.

Firstly install the required modules by typing command - 

npm i express mongoose file-upload

Then make 3 files named as server.js, addimage.js, Image.js.

1.server.js



  1. const express = require('express');
  2. const mongoose = require('mongoose');
  3. const app = express();
  4.  
  5. // connection to mongoose
  6. mongoose
  7. .connect('mongodb://localhost/db_name',{useNewUrlParser: true})
  8. .then( console.log('Connected to Mongoose') )
  9. .catch(err=> console.log(err))
  10.  
  11. //routes
  12. app.use('/upload',require('./routes/addimage')); //location of addimage.js
  13.  
  14. app.listen(5000);


      2- addimage.js
      1. const express = require('express');
      2. const router = express.Router();
      3. const fileUpload = require('express-fileupload');
      4. const Image = require('../models/Image'); // Image.js location
      5.  
      6. app.use(fileUpload());
      7.  
      8. // post image
      9. router.post('/',(req,res)=>{
      10. if(err) {
      11. return res.status(400).json({ msg:err })
      12. }
      13. else if(!req.files.file) {
      14. return res.status(400).json({ msg:'No file is uploaded' })
      15. }
      16. else {
      17. const file = req.files.file; //In req.files.file ,file is the name i.e - <input name="file" ... />
      18. // mention your own desired directory name
      const dir = `${__dirname}/client/public/uploads/${file.name}` ;
      1. file.mv( dir, err => {
      2. if (err) {
      3. console.error(err);
      4. return res.status(500).send(err);
      5. }
      6. const newImage = new Image ({ image : dir })
      7.  
      8. //Save Image in database
      9. newImage.save() .then(err =>{
      10. if(err) throw err; console.log('saved');
      11. })
      12. }
      13. }
      14.  module.exports = router;
    3. Image.js
    1. const mongoose = require('mongoose');
    2. const Schema = mongoose.Schema;
    3. const ImageSchema = new Schema({
    4. name : {
    5. type: String,
    6. required: true
    7. },
    8. date: {
    9. type: Date,
    10. default: Date.now
    11. }
    12. })
    13.  
    14. module.exports = Image = mongoose.model('image',ImageSchema)

Post a Comment

0 Comments