Answer the question
In order to leave comments, you need to log in
How not to save the image if it has not changed?
Hey!
I am making an admin panel. I form a formData and send it to the server.
In the router I do the following.
Created an array of expected fieldsformData.append("headerBg", headerBg);
const expectedFields = ['headerBg', 'previewImg', 'fullImg'];
req.inboxFileFields.push(file.fieldname);
for (let i = 0; i < expectedFields.length; i++) {
if (!req.inboxFileFields.includes(expectedFields[i])) {
update[expectedFields[i]] = null;
}
}
const router = require('express').Router();
const Project = require('../../../models/Project');
const multer = require('multer');
const slugify = require('slugify');
const uuidv4 = require('uuid/v4');
const allowedMimeTypes = ['image/jpeg'];
const expectedFields = ['headerBg', 'previewImg', 'fullImg'];
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/projects');
},
filename: function (req, file, cb) {
cb(null, uuidv4() + '-' + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
req.inboxFileFields.push(file.fieldname);
if (allowedMimeTypes.includes(file.mimetype)) {
cb(null, true);
} else {
return cb({message: 'Формат файла не верный'}, false);
}
};
const upload = multer({
storage,
limits: {fileSize: 1024 * 1024 * 5},
fileFilter
}).any();
router.put('/:slug', (req, res, next) => {
req.inboxFileFields = [];
const {slug} = req.params;
upload(req, res, async function (err) {
if (err) {
return res.status(400).json({message: err.message || 'Что-то пошло не так'});
}
let update = {
...req.body,
slug: slugify(req.body.name, {replacement: '-', remove: null, lower: true})
};
req.files.forEach((file) => {
const pathFile = `/${file.path.replace(/\\/g, '/')}`;
const field = file.fieldname;
update[field] = pathFile;
});
for (let i = 0; i < expectedFields.length; i++) {
if (!req.inboxFileFields.includes(expectedFields[i])) {
update[expectedFields[i]] = null;
}
}
const newProject = await Project.findOneAndUpdate({slug}, update, {new: true});
return res.status(202).json({newProject});
})
});
module.exports = router;
Answer the question
In order to leave comments, you need to log in
I see two solutions to the problem.
1) Convert the image to base64 format, i.e. text and compare with the original.
const bitmap = fs.readFileSync(file)
const base64Image = new Buffer(bitmap).toString('base64') // Получили изображение формата base64
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question