Creating folders by using object values - javascript

I am learning Nodejs, and I am trying to create folders for each new user.
The folder will be linked to the User name (when clicking on it will open folder/ftp)
I am using the Admin-bro interface.
Here is the User object.
const { model } = require("mongoose");
const User = model("User", {
name: String,
surname: String,
age: Number,
email: String,
description: String
});
module.exports = User;
User router:
const { Router } = require('express')
const paginate = require('../services/paginate.service')
const User = require('../models/user.model')
const dir = require('../routers/ftp')
const router = new Router()
const serializer = (user) => {
return user.toObject({ versionKey: false })
}
router.get('/', async (req, res) => {
const users = await paginate(User.find({}), req)
res.send(users.map(serializer))
})
router.post('/', async (req, res) => {
const user = await new User(req.body.user).save()
res.send(serializer(user))
})
module.exports = router
I have no idea how to create a folder for each new user I add, passing name_surname as the folder name.
I trying to create a router but failed.
This is what I tried:
"use strict";
module.exports = function(app) {
const fs = require("fs");
const path = require("path");
const multer = require("multer");
const storage = multer.diskStorage({
desctination: function(req, file, cb) {
const uploadDir = path.join(__dirname, "..", "..", `${Date.now()}`);
fs.mkdirSync(uploadDir);
cb(null, uploadDir);
},
filename: function(req, file, cb) {
cb(null, file.originalname);
}
});
const upload = multer({ storage });
const controller = require("../routers/createDir");
};
PS: there is no controller as I don't know what do to.
Please give me an advice or a link where I can learn how it's done. Thank you

User mkdrp node module package
var mkdirp = require('mkdirp');
mkdirp('/tmp/foo/bar/baz', function (err) {
if (err) console.error(err)
else console.log('pow!')
});

I am willing to pass the user name or id to the folder and create it dynamically, not manually. smth like this
const multer = require("multer");
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const { userId } = req.body;
const dir = `../uploads/${userId}`;
fs.exists(dir, exist => {
if (!exist) {
return fs.mkdir(dir, error => cb(error, dir));
}
return cb(null, dir);
});
},
filename: (req, file, cb) => {
const { userId } = req.body;
cb(null, `UserId-${userId}-Image-${Date.now()}.png`);
}
});
const upload = multer({ storage });

Related

File upload makes Node JS unresponsive with Multer

I am using Multer Node JS package to upload files to my app sever , the code is basically typical upload file code
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
But each time a file is being uploaded the Node server becomes unresponsive and frontend from other request doesnt receive any response from other APIs until the file is uploaded.
Whats the best way to tackle this ?
In your sample code, you must just send a response to the client by res.json() or res.end() :
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
res.status(204).end();
});
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
res.status(204).end();
});
i can give you an example of how i implemented an imageupload in my app. it the code to upload a profile image for a user. i am also using multer middleware so it shoulder be similiar for you:
code is as follows:
// multer middleware:
const multer = require('multer');
const MIME_TYPE_MAP = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
};
module.exports = storage = multer.diskStorage({
destination: (req, file, cb) => {
const isValid = MIME_TYPE_MAP[file.mimetype];
let error = new Error('invalid mime type');
if (isValid) {
error = null;
}
cb(error, 'images');
},
filename: (req, file, cb) => {
const name = file.originalname.toLowerCase().split(' ').join('-');
const ext = MIME_TYPE_MAP[file.mimetype];
if (name.includes('.' + ext)) {
cb(null, name)
} else {
cb(null, name + '.' + ext);
}
},
});
and here the code in the service handling the fileupload
// profile service in backend written in express
exports.uploadImage = (req, res, next) => {
const url = req.protocol + '://' + req.get('host');
profileRepository
.findOne({ _id: req.params.id })
.then((response) => {
const fetchedUser = response;
fetchedUser.imagePath = url + '/images/' + req.file.filename;
profileRepository
.updateOne({ _id: req.params.id }, fetchedUser)
.then((response) => {
return res.status(200).json({
message: 'profileimage updated',
});
})
.catch((error) => {
return res.status(500).json({
message: 'uploading image failed',
});
});
})
.catch((error) => {
return res.status(404).json({
message: 'fetching user failed',
});
});
};
then i use the middleware in my profile routes file like this:
// profile.routes.js
const express = require('express');
const ProfileController = require('./profileController');
const checkAuth = require('../middleware/checkAuth');
const router = express.Router();
const fileStorage = require('../middleware/fileStorage');
const multer = require('multer');
// imageUpload
router.post('/user/image/:id', checkAuth, multer({storage: fileStorage}).single('image'), ProfileController.image);
my Controller then calls the service function with the actual business logic like this:
// profile.controller.js
const profileService = require('./profileService');
exports.image = (req, res, next) => {
return profileService.uploadImage(req, res);
};
and finally my route is used by my app.js file like this:
// app.js
const express = require('express');
const profileRoutes = require('./profile/profileRoutes');
const app = express();
// set images path for saving images on server
app.use('/images', express.static(path.join('images')));
app.use('/api', profileRoutes);
module.exports = app;
i hope i was able to point you in the right direction with my example

UnhandledPromiseRejectionWarning: ObjectParameterError: Parameter "obj" to Document() must be an object

I am trying to upload a file and save it to a mongoose database. however, i keep getting an error
this is the error
this is the code i am using
const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const uuid = require('uuid').v4;
const FileSchema = require('../models/files');
const crypto = require('crypto');
//Set Storage Engine
const storage = multer.diskStorage({
destination: (req, response, callback) => {
callback(null, './public/uploads/');
},
filename: (request, file, callback) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (error, buf) => {
if(error){
return reject(error);
}
const ext = path.extname(file.originalname);
const id = uuid();
const filePath = `files/${id}${ext}`;
FileSchema.create(filePath)
.then(() => {
callback(null, filePath);
});
});
});
}
});
//init upload
const upload = multer({storage: storage});
router.post('/uploads', upload.array('files'),(req, response) => {
return response.json({ status: 'OK', uploaded: req.files.length});
});
module.exports = router;
please can anyone help?
thank you.

Cannot POST /images | MongoDB y Mongoose

I am developing a project with a friend in NodeJS and we are using express, Mongoose and when uploading images to the server it throws us this error: Cannot POST / images Here I leave the code in case someone can help me please:
const fs = ('fs-extra');
const path = ('path');
const md5 = ('md5');
const ctrl = {};
const Image = require('../models/image.js');
ctrl.create = (req, res) => {
const saveImage = async () => {
const imgUrl = randomNumber();
const images = await Image.find({ filename : imgUrl});
if(images.length > 0) {
saveImage()
} else {
const imageTempPath = req.file.path;
const ext = path.extname(req.file.originalname).toLowerCase();
const targetPath = path.resolve('/src/public/upload/${imgUrl}${ext}');
if(ext == '.png' || ext == '.jpg' || ext == '.gif' || ext == '.jpeg') {
await fs.rename(imageTempPath, targetPath);
const newImg = new Image({
filename: imgUrl + ext
});
const imageSaved = await newImg.save();
res.redirect('/images/' + imageSaved.uniqueId);
} else {
await fs.unlink(imageTempPath);
res.status(500).json({ error: 'Solo se permiten Imagenes'})
}
}
};
saveImage();
};
module.export = ctrl;
This is the controller that I have for uploading images and this is the model:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const path = require('path');
const ImageSchema = new Schema({
filename: { type: String }
});
ImageSchema.virtual('uniqueId')
.get(function () {
return this.filename.replace(path.extname(this.filename), '');
});
module.exports = mongoose.model('Image', ImageSchema);
And finally this is the route I use for uploading images (in addition to having some routes such as login and user registration):
const router = require('express').Router();
const passport = require('passport');
const multer = require('multer');
const path = require('path');
const fs = require('fs-extra');
const image = require('../controllers/image');
module.exports = app => {
router.post('/images', image.create);
}
router.get('/', (req, res, next) => {
res.render('index');
});
router.get('/signup', (req, res, next) => {
res.render('signup');
});
router.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true
}));
router.get('/signin', (req, res, next) => {
res.render('signin');
});
router.post('/signin', passport.authenticate('local-signin', {
successRedirect: '/profile',
failureRedirect: '/signin',
failureFlash: true
}));
module.exports = router;
router.use((req, res, next) => {
isAuthenticated(req, res, next);
next();
});
router.get('/profile', (req, res, next) => {
res.render('profile');
});
router.get('/logout', (req, res, next) => {
req.logout();
res.redirect('/');
});
function isAuthenticated(req, res, next) {
if(req.isAuthenticated()) {
return next();
}
res.redirect('/')
}
I would appreciate it very much if you could help me
Thank you.
You need to use multer to save images in MongoDB according to THIS article.
The important takeaway here is that our data type is a Buffer, which allows us to store our image as data in the form of arrays.
const multer = require('multer');
mongoose.connect(‘url_here’);
const Item = new ItemSchema(
{ img:
{ data: Buffer, contentType: String }
}
);
const Item = mongoose.model('Clothes',ItemSchema);
app.use(multer({ dest: ‘./uploads/’,
rename: function (fieldname, filename) {
return filename;
},
}));
app.post(‘/api/photo’,function(req,res){
var newItem = new Item();
newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
newItem.img.contentType = ‘image/png’;
newItem.save();
});
Or follow this post.
Store an image in MongoDB using Node.js/Express and Mongoose

How I can export multer module

I want to export modul multer to another file but the console returns an error to me.
TypeError: uploadImg.single is not a function
here is my multer.js
module.export = () => {
const multer = require("multer");
const storage = multer.diskStorage({
destination(req, file, cb) {
const url = `./uploads/catalog`;
cb(null, url);
},
filename(req, file, cb) {
file.originalname = "re_" + file.originalname;
cb(null, `${file.originalname}`);
}
});
const uploadImg = multer({
storage: storage
});
return uploadImg;
};
And here is a part of my routes file
const uploadImg = require("./../services/multer");
app.post("/catalog/upload/img", uploadImg.single("image"), async (req, res, next) => {
console.log(req.file);
});
You start with this: module.export = () => {... which means that you export the function.
So uploadImg is the function const uploadImg = require("./../services/multer"); and the only way how to call it is with uploadImg().
If you have everything else correct then uploadImg().single("image") should do the trick, but then it does not make sense to export it as function. If you use it in static context (which routes are), then you probably want something like this:
const multer = require("multer");
const storage = multer.diskStorage({
destination(req, file, cb) {
const url = `./uploads/catalog`;
cb(null, url);
},
filename(req, file, cb) {
file.originalname = "re_" + file.originalname;
cb(null, `${file.originalname}`);
}
});
const uploadImg = multer({
storage: storage
});
exports.uploadImg = uploadImg;
Then you can call it as following
const myMulter = require("./../services/multer");
app.post("/catalog/upload/img", myMulter.uploadImg.single("image"), async (req, res, next) => {
console.log(req.file);
});
You have a typo in multer.js
You should write module.exports = instead of module.export =

How to separate middleware in feathers?

I use to upload files a multer library with feathers. I try to separate logic from code and I want put upload code not in a index.js but in my case in pdf.js in middleware directory.
Below is my works index.js:
'use strict';
const pdf = require('./pdf');
const record = require('./record');
const records = require('./records');
const handler = require('feathers-errors/handler');
const notFound = require('./not-found-handler');
const logger = require('./logger');
const uploadPdf = require('./upload-pdf');
module.exports = function() {
// Add your custom middleware here. Remember, that
// just like Express the order matters, so error
// handling middleware should go last.
const app = this;
app.use('/rekord/:id.html', record(app));
app.use('/rekordy.html', records(app));
app.use('/pdf/:id', uploadPdf.single('file'), pdf(app));
app.use(notFound());
app.use(logger(app));
app.use(handler());
};
Here is upload-pdf.js file:
var multer = require('multer')
var storagePdf = multer.diskStorage({
destination: 'public/pdf',
filename: function (req, file, cb) {
var id = req.params.id
cb(null, id+'.pdf')
}
});
module.exports = multer({
storage: storagePdf,
fileFilter: function (req, file, cb) {
if (file.mimetype !== 'application/pdf') {
return cb(null, false, new Error('I don\'t have a clue!'));
}
cb(null, true);
}
});
And pdf.js file:
'use strict';
module.exports = function(app) {
return function(req, res, next) {
if (req.file) {
return res.end('Thank you for the file');
}
return res.end('false');
next();
};
};
I would like to combine upload-pdf.js and pdf.js into one file
Not particularly Feathers specific, just as with any other Express application you can put the code into their own modules:
'use strict';
const pdf = require('./pdf');
const record = require('./record');
const records = require('./records');
const handler = require('feathers-errors/handler');
const notFound = require('./not-found-handler');
const logger = require('./logger');
module.exports = function() {
// Add your custom middleware here. Remember, that
// just like Express the order matters, so error
// handling middleware should go last.
const app = this;
app.use('/rekord/:id.html', record(app));
app.use('/rekordy.html', records(app));
app.use('/pdf/:id', pdf.upload.single('file'), pdf.process(app));
app.use(notFound());
app.use(logger(app));
app.use(handler());
};
In pdf.js:
'use strict';
var multer = require('multer')
var storagePdf = multer.diskStorage({
destination: 'public/pdf',
filename: function(req, file, cb) {
var id = req.params.id
cb(null, id + '.pdf')
}
});
exports.upload = multer({
storage: storagePdf,
fileFilter: function(req, file, cb) {
if (file.mimetype !== 'application/pdf') {
return cb(null, false, new Error('I don\'t have a clue!'));
}
cb(null, true);
}
});
exports.process = function(app) {
return function(req, res, next) {
if (req.file) {
return res.end('Thank you for the file');
}
return res.end('false');
next();
};
};
The NodeJS module system docs are quite helpful to learn how it all fits together.

Categories

Resources