Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

storing an image file into buffer field with mongoose

// file-controller.js

const express = require('express');
const mongoose = require('mongoose');
const multer = require('multer');

const router = express.Router();

const multerStorage = multer.memoryStorage();
const upload = multer({ storage: multerStorage, });

const imageSchema = mongoose.Schema({
    image: { data: Buffer, contentType: String },
}, { timestamps: true });

const ImageModel = mongoose.model('images', imageSchema);

router.post('/upload', upload.single('image'), async (req, res, next) => {
    const image = { data: new Buffer.from(req.file.buffer, 'base64'), contentType: req.file.mimetype }
    const savedImage = await ImageModel.create(image);
    res.send(savedImage);
});

router.get('/getImage/:id', async (req, res, next) => {
    const { id: _id } = req.params;
    // If you dont use lean(), you wont decode image as base64
    const image = await ImageModel.findOne({ _id }).lean().exec();
    res.send(image);
});

module.exports = router;
Comment

PREVIOUS NEXT
Code Example
Javascript :: base64 to image nodejs 
Javascript :: delete axios token 
Javascript :: app script map fit markers 
Javascript :: canvas rectangle rounded corners 
Javascript :: how to read a file in javascript 
Javascript :: react Refused to execute inline script because it violates the following Content Security Policy directive 
Javascript :: how to get variable in local storage in javascript 
Javascript :: recursion in javascript 
Javascript :: fetch get request 
Javascript :: get odd elements of list javascript 
Javascript :: nuxt eslint prettier vetur 
Javascript :: swap two variables javascript 
Javascript :: slice method in js 
Javascript :: swap function javascript 
Javascript :: img src to file javascript 
Javascript :: discord.js 
Javascript :: angular router outlet 
Javascript :: Converting file to base64 on Javascript client side 
Javascript :: javaScript Math.log10() Method 
Javascript :: discord.js setactivity 
Javascript :: how to get random value less than in array js 
Javascript :: node js ffmpeg image to video 
Javascript :: debounce javascript 
Javascript :: react native grid view 
Javascript :: render XML in node 
Javascript :: footer react 
Javascript :: discord js 
Javascript :: javascript sort object 
Javascript :: siwtch case javascript 
Javascript :: javascript test is not a function 
ADD CONTENT
Topic
Content
Source link
Name
8+5 =