如何在Node.js中使用multer上传文件?

时间:2017-02-03 09:35:13

标签: javascript node.js file-upload multer

我想使用multer上传图片。但它没有用。这有什么不对?

此代码位于我的路线文件中。

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

这是我的邮寄路线。

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

4 个答案:

答案 0 :(得分:1)

试试这个,它对我有用。使用express和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);
        }
    });
  }
);

答案 1 :(得分:1)

确保安装包

  

npm install --save multer

您可以尝试以下方式, 在服务器端,在路由或控制器文件中配置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 });

在存储对象中,     目的地代表,文件将被上传。因此,请确保在项目目录中创建/ public / images / uploads路径。否则,您可能想要更改文件路径。

同样在存储对象中,filename代表,上传的文件名是什么。在这里,我使用原始文件名添加当前时间,以使所有文件名唯一。

现在在您想要的路由中,假设

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

现在您的文件已上传。确保客户端使用相同的名称,在这种情况下' image'。

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

这是一个单一文件上传程序。 对于多个文件

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

有关详细信息,请查看此link

答案 2 :(得分:0)

    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
 })

答案 3 :(得分:0)

试试这个code

npm install express multer --save

在 Server.js 中导入依赖

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

创建 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}`)
})

创建表单

<!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>

有关详细信息,请查看此 link