简体   繁体   中英

How to upload files using multer in Node.js?

I want to upload images using multer. But it is not working. What is wrong here?

This code is in my route file.

var multer  = require('multer');
var upload = multer({ dest: 'public/uploads/' });

And this is my post route.

router.post('/addNewFood', upload.single('avatar'),function (req, res, next) {
console.log(req.files);
});

Try this, it works for me. Used express and node.

 var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'public/uploads/') }, filename: function (req, file, cb) { cb(null, file.originalname) } }); var upload = multer({ storage: storage }).single('avatar'); router.post('/addNewFood', //Your authentication check,// function (req, res, next) { upload(req, res, function(err) { if (err) { res.redirect(req.headers.referer + "/error.html"); return; } if (!req.files) { res.redirect(req.headers.referer + "/error.html"); return; } else { //Implement your own logic if needed. Like moving the file, renaming the file, etc. res.redirect(req.headers.referer); } }); } );

Make sure you install the package

npm install --save multer

You can try the following way, In the server side, In your routes or controller file configure the multer:

var multer = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public/images/uploads')   
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname)      
    }
})
var upload = multer({ storage: storage });

In the storage object, destination is stand for, where the file will be uploaded. So make sure in your project directory, /public/images/uploads path is created. Otherwise you may want to change the file path.

Also in storage object filename is stands for, what will be the uploaded file name. Here I add the current time with the original file name to make the all file name unique.

Now in your desired routing, suppose

router.post('/', upload.single('image'), (req, res) => {
    //here your other task.
});

Now your file is uploaded. Make sure the client side is using the same name, In this case 'image'.

<input type="file" name="image" id="image" class='form-control'>

This is a single file upload procedure. For multiple files

router.post('/', upload.array(), function (req, res, next) {
  //your task goes here
});

For more information, check this link .

 const multer = require("multer"); function fileFilter(req, file, cb) { if (file.mimetype === "image/jpeg" || file.mimetype === "image/jpg" || file.mimetype === "image/png") { cb(null, true) } else { cb(null, false) } cb(new Error('I don\\'t have a clue!')) } var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, './uploads') }, filename: function (req, file, cb) { const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9) cb(null, file.fieldname + '-' + uniqueSuffix) } }) var upload = multer({ storage: storage, limits: { fieldSize: 1024 * 1024 * 5, fileFilter: fileFilter } }) router.post("/", upload.single("image_url"),(req, res) => { const new User=new User({ image_url: req.file.path })

Try this code

npm install express multer --save

Import Dependencies in Server.js

const express = require('express');
const multer = require('multer');
const path = require('path');

Create Server.js

const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const port = 3000

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, 'uploads/');
    },
   
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});
   
var upload = multer({ storage: storage })
   
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});
   
app.post('/', upload.array('multi-files'), (req, res) => {
  res.redirect('/');
});
   
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

Create Form

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>How To Upload Multiple Image Using Multer In Node.js - phpcodingstuff.com</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>Node js Express Multiple Image Upload using Multer Example - Tutsmake.com</h1>
    <form action="/" enctype="multipart/form-data" method="post">
      <input type="file" name="multi-files" accept='image/*' multiple>
      <input type="submit" value="Upload">
    </form>  
  </body>
</html>

For more information, check this link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM