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, 2022 in Node-js by Vaani
• 7,070 points
5,532 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, 2022 by Neha
• 9,020 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,880 points
23,137 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,880 points
5,441 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,880 points
13,722 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,880 points
2,934 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
1,900 views
0 votes
1 answer

Hyperledger Sawtooth vs Quorum in concurrency and speed Ask

Summary: Both should provide similar reliability of ...READ MORE

answered Sep 26, 2018 in IoT (Internet of Things) by Upasana
• 8,620 points
1,423 views
+1 vote
1 answer

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

yes all are over TCP/IP connections secured ...READ MORE

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

How to schedule a google meet and get the meet link in NodeJs?

To create a Google Meet, you'll need ...READ MORE

answered May 27, 2022 in Node-js by Neha
• 9,020 points
3,845 views
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, 2022 in Node-js by Neha
• 9,020 points
5,156 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP