Node.js and Multer - handle the purpose of the downloaded file in the callback function (req, res)

I am new to Node.js and I have recently encountered a very simple problem.

I use a module called multer, so users can upload images. In my web application, all users have a unique identifier, and I want the downloaded images to be stored in a directory with a name based on their identifier.

Example:

.public/uploads/3454367856437534 

Here is part of my routes.js file:

 // load multer to handle image uploads var multer = require('multer'); var saveDir = multer({ dest: './public/uploads/' + req.user._id, //error, we can not access this id from here onFileUploadStart: function (file) { return utils.validateImage(file); //validates the image file type } }); module.exports = function(app, passport) { app.post('/', saveDir, function(req, res) { id : req.user._id, //here i can access the user id }); }); } 

How can i access

 req.user._id 

out of

 function(req,res) 

So, can I use it with multer to create the corresponding id based directory?

EDIT Here's what I tried and didn't work:

 module.exports = function(app, passport) { app.post('/', function(req, res) { app.use(multer({ dest: './public/uploads/' + req.user._id })); }); } 
+5
source share
3 answers

Update

Several things have changed since I posted the original answer.

With multer 1.2.1 .

  • You need to use DiskStorage to indicate where and how the saved file is.
  • By default, multer will use the default directory for the operating system. In our case, as we are especially concerned with the location. We need to make sure that the folder exists before we can save the file there.

Note. You are responsible for creating the directory when you designate the destination as a function.

More here

 'use strict'; let multer = require('multer'); let fs = require('fs-extra'); let upload = multer({ storage: multer.diskStorage({ destination: (req, file, callback) => { let userId = req.user._id; let path = `./public/uploads//${userId}`; fs.mkdirsSync(path); callback(null, path); }, filename: (req, file, callback) => { //originalname is the uploaded file name with extn callback(null, file.originalname); } }) }); app.post('/', upload.single('file'), (req, res) => { res.status(200).send(); }); 

fs-extra to create a directory just in case it does not exist

Original answer

You can use changeDest

Function for renaming a directory to host downloaded files.

It is available from v0.1.8

 app.post('/', multer({ dest: './public/uploads/', changeDest: function(dest, req, res) { var newDestination = dest + req.user._id; var stat = null; try { stat = fs.statSync(newDestination); } catch (err) { fs.mkdirSync(newDestination); } if (stat && !stat.isDirectory()) { throw new Error('Directory cannot be created because an inode of a different type exists at "' + dest + '"'); } return newDestination } }), function(req, res) { //set your response }); 
+4
source

you can solve this by simply referring to the input name and renaming the path to its destination.

 app.use(multer({ dest: './standard_folder/', rename: function (fieldname, filename) { var pathHelper =''; if(fieldname =='otherKindOfFolderNeeded'){ pathHelper = '../../path/to/other/folder/'; } return pathHelper+uuid.v4()+Date.now(); }, onFileUploadStart: function (file) { console.log(file.originalname + ' is starting ...') }, onFileUploadComplete: function (file) { console.log(file.fieldname + ' uploaded to ' + file.path) done=true; } }) ); 
0
source

You can accomplish this by using multer to handle the dynamic creation of the boot directory. Before sending the file name, you must call the input parameter (for which you want to create a directory).

 var express = require('express'); var app = express(); var multer = require('multer'); var fs = require('fs'); var mkdirp = require('mkdirp'); var bodyParser = require('body-parser'); app.use(bodyParser.json({limit: '5mb'})); app.use( bodyParser.json() ); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true, limit: '5mb' })); var storage = multer.diskStorage({ destination: function (req, file, callback) { var Id = req.body.id; upload_path = "./"+Id; mkdirp(upload_path, function (err) { if (err) console.error(err) else { console.log('Directory created'); //setting destination. callback(null, upload_path); } }); }, filename: function (req, file, callback) { callback(null, file.orginalname) } }); //multer setting and getting paramaters. var upload = multer({ storage : storage }).single('upload_file'); //creating request for upload file app.post('/uploadFile', function(req, res){ res.set({ 'content-type': 'application/json; charset=utf-8' }); res.header("Content-Type", "application/json; charset=utf-8"); res.header("Access-Control-Allow-Origin", "*"); res.charset = 'utf-8'; //function upload_process(){ upload(req, res, function(err){ if(err){ console.log('Error-->'); console.log(err); res.json({"status": "Failure", "message":'There was a problem uploading your files.'+err}); return; } else{ console.log("fieldname"+req.files.length); if( req.files.length != 0){ res.json({"status" : "Success", "message":'Your files are uploaded.'}); console.log('File uploaded!'); } else{ console.log("No file uploaded. Ensure file is uploaded."); res.json({"status" : "Failure", "message" : 'No file uploaded. Ensure file is uploaded.'}); } } }); }); }); 

Hope this helps! Happy coding

0
source

Source: https://habr.com/ru/post/1207977/


All Articles