ISHAN AJMERI
ISHAN AJMERI

Reputation: 23

get the file which send by the multer in nodejs?

this is my upload.js code:

var multer = require('multer');
var express = require('express');
const router = express.Router();

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads');
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now());
  },
});

var upload = multer({ storage: storage });

router.post('/', upload.single('file'), (req, res, next) => {
  const file = req.file;
  if (!file) {
    const error = new Error('Please upload a file');
    error.httpStatusCode = 400;
    return next(error);
  }
  res.send(file);
});

module.exports = router;

can anyone tell what will be the router.get? so that I can get an image in the response.

Upvotes: 2

Views: 1652

Answers (2)

eol
eol

Reputation: 24565

You could simply statically serve the uploads-folder. By doing this you don't need an actual get-handler, instead you define the express.static-middleware

app.use(express.static('uploads'));

Now the client can simply perform a request to http://yourServer/<imagename>-<timestamp> and the file will be served automatically.

EDIT:

In order to get the generated file name to the client, you could do the following:

Instead of doing res.send(file); in your post-handler, you could return a json containing the generated filename, which the client then can request:

app.post("/upload", upload.single('image'), (req, res) => {
    res.json({uploadedFile: req.file.filename})
});

One more thing: you will lose the file's extension by with your filename-function. In order to keep the extension you could do (make sure to require the path-module):

filename: (req, file, cb) => {
    const extension = path.extname(file.originalname);
    cb(null, `${file.fieldname}-${Date.now()}${extension}`);
}

Upvotes: 1

Alex Shchur
Alex Shchur

Reputation: 751

eol's answer is good, but if you need to maintain access, the controller might look something like this:

res.writeHead(200,{'content-type':'image/jpg'});
fs.createReadStream('./image/demo.jpg').pipe(res);

Upvotes: 0

Related Questions