multer上传无法正常工作

时间:2018-04-13 08:29:12

标签: javascript node.js express multer

我正在尝试使用multer来使用文件上传功能。 我总是收到404错误,我该如何解决?

  

这是我的app.js



var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

var session = require('express-session');
var flash = require('connect-flash');
var mongoose = require('mongoose');

var multer = require('multer');

app.use(multer({
  dest: './uploads/'
}).single('singleInputFileName'));




  

这是我的router.js

router.post('/', function(req, res) {
   console.dir(req.files);
});
  

这就是形式:

form(action='/' enctype='multipart/form-data')
 input(type='file' name='singleInputFileName')
 input(type='submit' value='Upload photo')

编辑:我已将此脚本添加到app.js



app.post('/fileuploads', function(req, res) {
  upload(req, res, function(err) {
    console.log(req.body);
    console.log(req.files);
    if (err) {
      return res.end("Error uploading file.");
      console.log(err);
    }
    res.end("File is uploaded");
  });
});




2 个答案:

答案 0 :(得分:0)

这是multer文件上传的工作片段,我已经使用以下代码对邮递员进行了测试,请查看并相应地进行更改。

  

app.js

// NodeJS Core dependencies
var express = require('express');
var app = express();
var router = express.Router();
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var createError = require('http-errors');
var session = require('express-session');
var flash = require('connect-flash');
var mongoose = require('mongoose');
// Router file in which routes implemented
var index = require("./routes/index")(app, router);
// Add routers in middleware
app.use("/", index);
// Listen application on 3000 Port
app.listen(3000, function () {
    console.log("application running on port 3000");
});
  

index.js

// NodeJS module dependencies
var multer = require('multer');
var storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, `${process.cwd()}/uploads/`)
    },
    filename: (req, file, cb) => {
        cb(null, file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1].toLowerCase())
    }
});
var upload = multer({ storage: storage });
// Export routes
module.exports = function (app, router) {
    router.post('/fileupload', upload.single('avatar'), (req, res, next) => {
        res.status(200).json({message: `File uploaded successfully on '${process.cwd()}/uploads/${req.file.filename}`});
    });
    return router;
}
  

的package.json

{
  "name": "nodejs-multer",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "connect-flash": "0.1.1",
    "cookie-parser": "1.4.3",
    "express": "4.16.3",
    "express-session": "1.15.6",
    "mongoose": "5.0.14",
    "moongoose": "0.0.5",
    "morgan": "1.9.0",
    "multer": "1.3.0",
    "nodemon": "1.17.3"
  }
}

答案 1 :(得分:0)

我认为表单的行为不正确,请尝试' / fileuploads'

form(action='/fileuploads' enctype='multipart/form-data')
input(type='file' name='singleInputFileName')
input(type='submit' value='Upload photo')