How to set different destinations in nodejs using multer

0 votes

I'm trying to upload any file using Multer package. It's working fine when I use following code in my server.js file.

var express = require('express'),
    app = express(),
    multer = require('multer');
app.configure(function () {
    app.use(multer({
        dest: './static/uploads/',
        rename: function (fieldname, filename) {
            return filename.replace(/\W+/g, '-').toLowerCase();
        }
    }));
    app.use(express.static(__dirname + '/static'));
});

app.post('/api/upload', function (req, res) {
    res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name});
});

var server = app.listen(3000, function () {
    console.log('listening on port %d', server.address().port);
});

What I want is to store file at different locations. I had tried following code but it does not work for me.

var express = require('express'),
    app = express(),
    multer = require('multer');
app.configure(function () {
    app.use(multer({
        //dest: './static/uploads/',
        rename: function (fieldname, filename) {
            return filename.replace(/\W+/g, '-').toLowerCase();
        }
    }));
    app.use(express.static(__dirname + '/static'));
});

app.post('/api/pdf', function (req, res) {
    app.use(multer({ dest: './static/pdf/'}));
    res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name});
});

app.post('/api/image', function (req, res) {
    app.use(multer({ dest: './static/image/'}));
    res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name});
});

app.post('/api/video', function (req, res) {
    app.use(multer({ dest: './static/video/'}));
    res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name});
});

var server = app.listen(3000, function () {
    console.log('listening on port %d', server.address().port);
});

Means, if I hit http://localhost:3000/api/pdf file should store at 'pdf' folder, if I hit http://localhost:3000/api/video file should store at 'video' folder.

Is there any way to achieve this aim?

Jun 13 in Node-js by Vaani
• 6,820 points
23 views

1 answer to this question.

0 votes

With multer 1.2.1.

  1. You need to use DiskStorage to specify where & how of the stored file.
  2. By default, multer will use the operating system's default directory. In our case, since we are particular about the location. We need to ensure that the folder exists before we could save the file over there.

Note: You are responsible for creating the directory when providing destination as a function.

For more information.

'use strict';

let multer = require('multer');
let fs = require('fs-extra');

let upload = multer({
  storage: multer.diskStorage({
    destination: (req, file, callback) => {
      let type = req.params.type;
      let path = `./uploads/${type}`;
      fs.mkdirsSync(path);
      callback(null, path);
    },
    filename: (req, file, callback) => {
      //originalname is the uploaded file's name with extn
      callback(null, file.originalname);
    }
  })
});

app.post('/api/:type', upload.single('file'), (req, res) => {
  res.status(200).send();
});

fs-extra for creating directory, follow this link.

answered Jun 13 by Neha
• 8,560 points

Related Questions In Node-js

0 votes
1 answer

How to extract request http headers from a request using NodeJS connect?

Hello @kartik, To see a list of HTTP ...READ MORE

answered Jul 15, 2020 in Node-js by Niroj
• 82,720 points
13,522 views
0 votes
1 answer

How to set custom favicon in Express?

Hello @kartik,  Just use: app.use('/favicon.ico', express.static('images/favicon.ico')); OR In express: //you probably ...READ MORE

answered Jul 17, 2020 in Node-js by Niroj
• 82,720 points
2,930 views
0 votes
1 answer

How to get the _id of inserted document in Mongo database in NodeJS?

Hello @kartik, A shorter way than using second ...READ MORE

answered Sep 7, 2020 in Node-js by Niroj
• 82,720 points
7,980 views
0 votes
1 answer

How to run app.js in nodejs?

Hello @kartik, Assuming I have node and npm properly installed on the ...READ MORE

answered Oct 13, 2020 in Node-js by Niroj
• 82,720 points
1,164 views
0 votes
1 answer

Truffle tests not running after truffle init

This was a bug. They've fixed it. ...READ MORE

answered Sep 11, 2018 in Blockchain by Christine
• 15,790 points
962 views
0 votes
1 answer
0 votes
1 answer

Protocols used in a distributed/dlt system for the nodes to establish communication

yes all are over TCP/IP connections secured by TLS encryption in hashgraph architecture-hashgraph, ...READ MORE

answered Aug 6, 2018 in Blockchain by aryya
• 7,440 points
622 views
0 votes
1 answer
0 votes
1 answer

How to use pino-transport in nodejs for logs?

Ensure that you have a recent version ...READ MORE

answered Jun 9 in Node-js by Neha
• 8,560 points
37 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP