I am using cloudinary with node and multer
I successfully managed to store images but i noticed each time i upload an image it creates two copies : one with the public_id as a name (in the assets) and the other with the original name(in 'profiles' folder).
I want to delete both whenever i upload a new image but it only deletes the one in the assets and don't delete the one in the 'profiles' picture.
My upload route looks like this
import path from "path";
import express from "express";
import dotenv from "dotenv";
import cloudinary from "cloudinary";
import { CloudinaryStorage } from "multer-storage-cloudinary";
import multer from "multer";
dotenv.config();
const cloud = cloudinary.v2;
const router = express.Router();
cloud.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
const storage = new CloudinaryStorage({
cloudinary: cloud,
params: {
folder: "profiles",
transformation: { gravity: "center", height: 300, width: 300, crop: "fill" },
public_id: (req, file) =>
`${file.originalname.split(".")[0]}-${Date.now()}`,
},
});
function checkFileType(file, cb) {
const filetypes = /jpg|jpeg|png/;
const extname = filetypes.test(
path.extname(file.originalname).toLocaleLowerCase()
);
const mimetype = filetypes.test(file.mimetype);
if (extname && mimetype) {
return cb(null, true);
} else {
cb(null, false);
}
}
const upload = multer({
storage,
fileFilter: function (req, file, cb) {
checkFileType(file, cb);
},
});
router.post("/", upload.single("image"), async (req, res) => {
try {
const result = await cloud.uploader.upload(req.file.path)
res.send(result);
} catch(error) {
console.log(error)
}
});
export default router;
And the delete route
import express from "express";
import dotenv from "dotenv";
import cloudinary from "cloudinary";
dotenv.config();
const cloud = cloudinary.v2;
const router = express.Router();
cloud.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
router.post('/:id', async (req, res) =>{
try {
await cloud.uploader.destroy(req.params.id);
// await cloud.uploader.destroy(`/profiles/${req.params.id}`);
res.send(result);
} catch (err) {
return res.status(500).json({msg: err.message})
}
})
export default router;
Can anyone help ?
In case anyone face the same issue
I was sending the image twice in the upload route
Just change it to this
router.post("/", upload.single("image"), async (req, res) => {
try {
res.json(req.file);
} catch (error) {
console.log(error);
}
});
Related
Hope you're doing well.
I have a question regarding my Node.js backend app. I am trying to upload an image and a video but I get this error :
"error": "Unexpected field" on postman
Here is my code :
create:(req,res)=>{
console.log("Test1");
console.log("Test1bis");
//const exercise=JSON.parse(req.body.exercise);
//delete exercise._id;
console.log("Test2")
var exerciseB = new Exercise({
...req.body,
image:`${req.protocol}://${req.get('host')}/images/exercise/${req.file.filename1}`,
video:`${req.protocol}://${req.get('host')}/videos/exercise/${req.file.filename2}`
})
console.log("Test3")
exerciseB.save((err,exercise)=>{
if(err){
console.log("C'est le 2eme err");
return res.status(500).json({
status:500,
message:err.message
})
}
console.log("Ca arrive jusqu'au 200");
return res.status(201).json({
status:200,
message:"Exercise Created Successfully !"
})
})
}
And this is the multer file I am using to generate the image in a separate file ( I am using a similar multer for the video) :
const multer=require('multer');
const MIME_TYPES={
'image/jpg':'jpg',
'image/jpeg':'jpg',
'image/png':'png'
}
const storage=multer.diskStorage({
destination:(req,file,callback)=>{
callback(null,'public/images/exercise');
},
filename1:(req,file,callback)=>{
var name=Math.floor(Math.random()*Math.floor(123456789)).toString();
name+=Math.floor(Math.random()*Math.floor(123456789)).toString();
name+=Math.floor(Math.random()*Math.floor(123456789)).toString();
name+=Math.floor(Math.random()*Math.floor(123456789)).toString();
name+=Date.now()+".";
const extension=MIME_TYPES[file.mimetype];
name+=extension;
callback(null,name)
}
})
module.exports=multer({storage}).single('image');
And here is my postman screenshot :
This is my other multer file for the video :
const multer=require('multer');
const MIME_TYPES={
'video/mp4':'mp4',
'video/mpeg':'mpeg',
'video/ogg':'ogv',
'video/mp2t':'ts',
'video//webm':'webm',
}
const storage=multer.diskStorage({
destination:(req,file,callback)=>{
callback(null,'public/videos/exercise');
},
filename2:(req,file,callback)=>{
var name=Math.floor(Math.random()*Math.floor(123456789)).toString();
name+=Math.floor(Math.random()*Math.floor(123456789)).toString();
name+=Math.floor(Math.random()*Math.floor(123456789)).toString();
name+=Math.floor(Math.random()*Math.floor(123456789)).toString();
name+=Date.now()+".";
const extension=MIME_TYPES[file.mimetype];
name+=extension;
callback(null,name)
}
})
module.exports=multer({storage}).single('video');
And this is my routes file :
var express = require('express');
var router = express.Router();
var exerciseController = require('../controllers/exerciseController');
const multerImage=require('../middlewares/multer-image');
const multerVideo=require('../middlewares/multer-video');
/* GET home page. */
router.get('/show', exerciseController.show);
router.post('/create',multerImage, multerVideo, exerciseController.create);
router.put('/update/:id',multerImage, exerciseController.update);
module.exports = router;
I think I can't proceed the way I do in the routes file in the second router call.
Hope you can help me ! Thank you for trying too :)
remove this line
module.exports=multer({storage}).single('image');
and set this line because image is not your name filename1/filename2 your image name
module.exports=multer({storage}).single('filename1');
This is running code but make sure you already created dir public/uploads, you edit your upload location and upload multiple file
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const app = express();
app.use(bodyParser.urlencoded({ limit: '10mb', extended: true }))
app.use(bodyParser.json({ limit: '10mb', extended: true }))
app.use(express.static('public/uploads'))
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "public/uploads")
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
})
app.post('/', (req, res) => {
const upload = multer({ storage: storage }).single('image_url');
upload(req, res, function (err) {
if (err) {
console.log(err)
return
}
var exerciseB = new Exercise({
...req.body,
image: `${req.protocol}://${req.get('host')}/images/exercise/${req.file.originalname}`,
video: `${req.protocol}://${req.get('host')}/videos/exercise/${req.file.originalname}`
})
exerciseB.save((err, exercise) => {
if (err) {
console.log("C'est le 2eme err");
return res.status(500).json({
status: 500,
message: err.message
})
}
console.log("Ca arrive jusqu'au 200");
return res.status(201).json({
status: 200,
message: "Exercise Created Successfully !"
})
})
})
})
app.listen(9001, () => {
console.log(`listening on port ${9001}`)
});
I am trying to upload images in an express server using multer, however, uploading images using postman using the route below, gives the json message { msg: 'image uploaded successfully' } (i.e., the route is reached correctly), but req.file gives undefined. Why? the related file structure is as follows, to make sure I am referencing the destination correctly:
-backend
--routes
---uploadRoutes.js
--server.js
-frontend
-uploads
uploadRoutes.js
import path from 'path';
import express from 'express';
import multer from 'multer';
const router = express.Router();
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, 'uploads');
},
filename(req, file, cb) {
cb(
null,
`${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
);
},
});
function checkFileType(file, cb) {
const filetypes = /jpg|jpeg|png/;
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if (extname && mimetype) {
return cb(null, true);
} else {
cb('Images only!');
}
}
const upload = multer({
storage,
fileFilter: function (req, file, cb) {
checkFileType(file, cb);
},
});
router.post('/', upload.single('image'), (req, res) => {
console.log(req.file);
try {
res.status(200).json({ msg: 'image uploaded successfully' });
} catch (error) {
console.error(error.message);
}
// res.send(`/${req.file.path}`);
});
export default router;
just check the header and body form-data request, because your code is correctly if you have this line in the app file
app.use("/uploads", express.static("uploads"));
header of request
I am new in ExpressJs and working on creating api for one of a dashboard created in reactjs. There is a form in a dashboard which is collecting some of information from the users like "title", "description" and "image". I have created an express server to collect that information and to save it into mongodb. For images What I have done is that, I am uploading image to Cloudinary and storing uploaded url and public_id into database.
So after following some of tutorials I have done something like this.
index.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const db = require("./db");
// Api router import goes here
const sectionTypesRouter = require("./routes/section-types-router");
const app = express();
const apiPort = 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(bodyParser.json());
db.on("error", console.error.bind(console, "MongoDB connection error:"));
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.use("/api", sectionTypesRouter);
app.listen(apiPort, () => console.log(`Server running on port ${apiPort}`));
Than, First I have create a file multer.js :
const multer = require("multer");
const storage = multer.diskStorage({
destination: "public/uploads",
filename: (req, file, cb) => {
cb(null, file.fieldname + "-" + Date.now());
},
});
const fileFilter = (req, file, cb) => {
if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
cb(null, true);
} else {
//reject file
cb({ message: "Unsupported file format" }, false);
}
};
const upload = multer({
storage: storage,
fileFilter: fileFilter,
});
module.exports = upload;
Below is my api router section-type-router.js :
const express = require("express");
const upload = require("../utils/multer");
const SectionTypesCtrl = require("../controllers/section-types-ctrl");
const router = express.Router();
router.post(
"/section-type",
upload.single("image"),
SectionTypesCtrl.createSectionType
);
router.get("/section-types", SectionTypesCtrl.getSectionTypes);
module.exports = router;
This is the section-type-ctrl.js :
const SectionType = require("../models/section-type-model");
const fs = require("fs");
const path = require("path");
const cloudinaryUploader = require("../utils/cloudinaryUploader");
const createSectionType = async (req, res) => {
const body = req.body;
if (!body) {
return res.status(400).json({
success: false,
error: "Required parameter are missing",
});
}
cloudinaryUploader
.uploads(req.file.path, "Section-Types")
.then((result) => {
const sectionType = new SectionType({
title: body.title,
description: body.description,
image: {
url: result.url,
publicId: result.public_id,
},
});
sectionType
.save()
.then(() => {
return res.status(201).json({
success: true,
id: sectionType._id,
message: "Section type created!",
});
})
.catch((error) => {
return res.status(400).json({
error,
message: "Section type not created!",
});
});
})
.catch((error) => {
res.status(500).send({
message: "failure",
error,
});
});
};
module.exports = {
createSectionType,
};
And lastly this is cloudinaryUpload.js :
const cloudinary = require("../config/cloudinary");
exports.uploads = (file, folder) => {
return new Promise((resolve) => {
cloudinary.uploader.upload(
file,
{
resource_type: "auto",
folder: folder,
},
(err, result) => {
if (!err) {
resolve({
url: result.url,
public_id: result.public_id,
});
} else {
throw err;
}
}
);
}).catch((error) => {
throw error;
});
};
Now, everything is working properly. Images is uploading to the cloudinary and returned url and public_id is storing in database. But the problem is that image that I have uploaded is also upload on local directory public/uploads/. This will may create a storage issue while host a site. So Is there any best way to upload image directly to the cloudinary without creating a copy in local directory which also should work on production mode ?
In your example, the file is being stored to public/uploads on your server because you're telling multer to do so via multer.diskStorage
As #Molda's comment above says, you can avoid this by using the multer-storage-cloudinary package to have Multer store the file in Cloudinary automatically.
Another possibility is to change how you're using Multer so it doesn't store the file anywhere, then take the uploaded file while it's in memory and pass it to Cloudinary's SDK as a stream.
There's an example of this in this blog post on the Cloudinary site: https://cloudinary.com/blog/node_js_file_upload_to_a_local_server_or_to_the_cloud
In your case, you can stop using multer.diskStorage, in favour of just using multer() then use streamifier or another library to turn the uploaded file into a stream, and pass that to cloudinary.uploader.upload_stream()
I implemented the server to receive file using the lib multer, it works for photographs(PNG, JPEG) but not for PDF ... acctually i can receive but the file got corrupted. If someone could help me i appreciate :)
MulterĀ“s config :
import crypto from 'crypto';
import multer from 'multer';
import { extname, resolve } from 'path';
export default {
storage: multer.diskStorage({
destination: resolve(__dirname, '..', '..', 'tmp', 'uploads'),
filename: (req, file, cb) => {
crypto.randomBytes(16, (err, raw) => {
if (err) return cb(err);
return cb(null, raw.toString('hex') + extname(file.originalname));
});
},
}),
};
Middleware :
middlewares() {
this.server.use(cors());
this.server.use(express.json());
this.server.use(
'/files',
express.static(resolve(__dirname, '..', '..', 'tmp', 'uploads'))
);
}
Routes:
const routes = new Router();
const upload = multer(multerConfig);
routes.post('/files', upload.single('file'), FileController.store);
FileController:
import File from '../models/File';
class FileController {
async index(req, res) {
const file = await File.findByPk(req.params.id);
res.json(file);
}
async store(req, res) {
const { originalname: name, filename: path } = req.file;
const file = await File.create({
name,
path,
});
return res.json(file);
}
}
export default new FileController();
I am trying to create a user profile in express.js and MongoDB. I am using multer for image uploading. Multer middleware always uploads the image before verifying my user data. If user validation is failed, nevertheless image is uploaded. But, I want to upload an image after validating user data. That means, I will check user data in the controller, and if it is valid then I will upload image and store user data to MongoDB. How can I do that? Thanks in advance!
multerConfig.js
exports.multerConfig = (multer) => {
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './uploads/');
},
filename: (req, file, cb) => {
cb(null, 'img-' + new Date().toISOString() + '-' + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
(file.mimetype === 'image/png' || file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg')
? cb(null, true)
: cb(null, false)
};
return multer({
storage: storage,
limits: { fileSize: 1048576 },
fileFilter: fileFilter
});
};
user.js(Routes)
const multer = require('multer');
const express = require('express');
const userController = require('../controllers/user');
const { multerConfig } = require('../utility/multerConfig');
const validateObjectId = require('../middleware/validateObjectId');
const asyncErrorHandler = require('../middleware/asyncErrorHandler');
const router = express.Router();
const upload = multerConfig(multer);
router.post('/', upload.single('image'), asyncErrorHandler(userController.createUser));
module.exports = router;
user.js(Controller)
const { User, validate } = require('../models/user');
const { deleteFile } = require('../utility/fileUtility');
const { failed, success } = require('../utility/utility');
exports.createUser = async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send({ ...failed, message: error.details[0].message });
const { name, address, mobile, email, password } = req.body;
if (!req.file) return res.status(400).send({ ...failed, message: `you have to upload an image!` });
const isUserExist = await User.find().or([{ mobile }, { email }]);
if (isUserExist.length > 0) return res.status(409).send({ ...failed, message: `${name} is already exists!` });
const image = req.file.path;
const newUser = new User({ name, address, mobile, email, password, image });
const savedUser = await newUser.save();
if (!savedUser) return res.status(500).send({ ...failed, message: `user ${name} is failed to save!` });
res.send({
...success,
data: savedUser,
message: `user ${name} is saved successfully`
});
};
You can use two multer middleware (one for parsing text, one for uploading your file).
Let's say you have a form with a name (text field) and avatar (file field), you can do this:
var express = require('express');
var multer = require('multer');
var app = express();
var upload = multer({ dest: 'uploads/' });
app.post('/profile',
upload.none(), function (req, res, next) {
// validate `req.body.name` here
// and call next(err) if it fails
next();
},
upload.single('avatar'), function (req, res, next) {
// file is now uploaded, save the location to the database
res.end('done!');
});
app.listen(9000);