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 -
- <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
- const express = require('express');
- const mongoose = require('mongoose');
- const app = express();
- // connection to mongoose
- mongoose
- .connect('mongodb://localhost/db_name',{useNewUrlParser: true})
- .then( console.log('Connected to Mongoose') )
- .catch(err=> console.log(err))
- //routes
- app.use('/upload',require('./routes/addimage')); //location of addimage.js
- app.listen(5000);
- const express = require('express');
- const router = express.Router();
- const fileUpload = require('express-fileupload');
- const Image = require('../models/Image'); // Image.js location
- app.use(fileUpload());
- // post image
- router.post('/',(req,res)=>{
- if(err) {
- return res.status(400).json({ msg:err })
- }
- else if(!req.files.file) {
- return res.status(400).json({ msg:'No file is uploaded' })
- }
- else {
- const file = req.files.file; //In req.files.file ,file is the name i.e - <input name="file" ... />
- // mention your own desired directory name
- file.mv( dir, err => {
- if (err) {
- console.error(err);
- return res.status(500).send(err);
- }
- const newImage = new Image ({ image : dir })
- //Save Image in database
- newImage.save() .then(err =>{
- if(err) throw err; console.log('saved');
- })
- }
- }
- module.exports = router;
- const mongoose = require('mongoose');
- const Schema = mongoose.Schema;
- const ImageSchema = new Schema({
- name : {
- type: String,
- required: true
- },
- date: {
- type: Date,
- default: Date.now
- }
- })
- module.exports = Image = mongoose.model('image',ImageSchema)
2- addimage.js
const dir = `${__dirname}/client/public/uploads/${file.name}` ;
3. Image.js
0 Comments