此NodeJs multer文件上传代码有什么问题?

时间:2018-11-05 08:57:01

标签: node.js multer

我正在尝试学习Node的multer库,该库对于通过API调用上传文件非常有用,
我有一个基本的快速应用程序设置,正在侦听4300端口,
使用multer的diskStorage函数来定义我希望存储上传文件的文件系统位置。

并公开了3个端点-
第一个用于接受单个文件上传,密钥名-singleFile
第二个用于接受键名称为 keyname-multipleFiles
的文件数组 第三个用于接受具有不同键名的单个/数组文件的数组。

我指的是以下内容
1. https://www.npmjs.com/package/multer
2. https://medium.com/@bmshamsnahid/nodejs-file-upload-using-multer-3a904516f6d2

var express = require('express')
var cors = require('cors')
var multer  = require('multer')
var async = require('async')

var app = express();
app.use(cors());
app.listen(4300, function () {
    console.log('listening on port 4300!');
});


var storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, '/home/user/Desktop/node/')
    },
    filename: (req, file, cb) => {
      cb(null, file.fieldname + '-' + Date.now())
    }
});
var upload = multer({storage: storage});

app.post('/single', upload.single('singleFile'), function (req, res, next) {
    console.log(req.file.filename);
    res.send({'message': 'File received! k thnkx bye!'});
});

app.post('/multiple', upload.array('multipleFiles', 3), function (req, res, next) {
    console.log(req.files);

    async.each(req.files, function (temp, callback) {
       console.log(temp);
    }, function (err) {
       if (err) {
           console.log('Error ' + err);
       } else {
        console.log('Success');
       }
    });

    res.send({'message': 'Files received! k thnkx bye!'});
});

var cpUpload = upload.fields([{ name: 'singleFile', maxCount: 1 }, { name: 'multipleFiles', maxCount: 3 }])
app.post('/fields', cpUpload, function (req, res, next) {
    console.log(req);
    res.send({'message': 'Files received! k thnkx bye!'});
});

以下是使用Postman工具进行的API调用- 1。单一文件上传API- enter image description here

2。多个文件上传API- enter image description here

我在控制台上收到“ TypeError:无法读取未定义的属性'filename'”的日志。可能是由于某些错误。

调试控制台-

/home/user/.nvm/versions/node/v10.11.0/bin/node --inspect-brk=10250 Node-Tutorials/Apps/multer.js 
Debugger listening on ws://127.0.0.1:10250/87170633-e582-4ac5-b099-0d2e6d090a7f
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
listening on port 4300!
TypeError: Cannot read property 'filename' of undefined
    at /home/user/office/node-crud-app/Node-Tutorials/Apps/multer.js:23:26
    at callbacks (/home/user/office/node-crud-app/node_modules/express/lib/router/index.js:164:37)
    at multerMiddleware (/home/user/office/node-crud-app/node_modules/multer/lib/make-middleware.js:18:41)
    at callbacks (/home/user/office/node-crud-app/node_modules/express/lib/router/index.js:164:37)
    at param (/home/user/office/node-crud-app/node_modules/express/lib/router/index.js:138:11)
    at pass (/home/user/office/node-crud-app/node_modules/express/lib/router/index.js:145:5)
    at Router._dispatch (/home/user/office/node-crud-app/node_modules/express/lib/router/index.js:173:5)
    at Object.router [as handle] (/home/user/office/node-crud-app/node_modules/express/lib/router/index.js:33:10)
    at next (/home/user/office/node-crud-app/node_modules/connect/lib/proto.js:193:15)
    at cors (/home/user/office/node-crud-app/node_modules/cors/lib/index.js:188:7)

有人可以帮助修复我的代码,以将文件下载到文件系统上吗?

2 个答案:

答案 0 :(得分:0)

尝试安慰req.files.filename。

我在req.files.filename中找到了文件名。

更正-req.files是对象的数组。

答案 1 :(得分:0)

  

console.logs上的“ TypeError:无法读取未定义的属性'filename'”可能是一些错误。

如果file为空,则有可能。

error message when not uploading a file

处理案件,

'use strict';

var express = require('express')
var cors = require('cors')
var multer = require('multer')
var async = require('async')

var app = express();
app.use(cors());
app.listen(4300, function () {
  console.log('listening on port 4300!');
});


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

const params = {
  '/single': 'file',
  '/multiple': 'files'
};

function validate(req, res, next) {
  let param = params[req.url];
  if (!req[param]) {
    return res.send({
      errors: {
        message: `${param} cant be empty`
      }
    });
  }
  next();
}

app.post('/single', upload.single('singleFile'), validate, function (req, res, next) {
  console.log(req.file.filename);
  res.send({'message': 'File received! k thnkx bye!'});
});

app.post('/multiple', upload.array('multipleFiles', 3), validate, function (req, res, next) {
  console.log(req.files);

  async.each(req.files, function (temp, callback) {
    console.log(temp);
  }, function (err) {
    if (err) {
      console.log('Error ' + err);
    } else {
      console.log('Success');
    }
  });

  res.send({'message': 'Files received! k thnkx bye!'});
});

var cpUpload = upload.fields([{name: 'singleFile', maxCount: 1}, {name: 'multipleFiles', maxCount: 3}])
app.post('/fields', cpUpload, function (req, res, next) {
  console.log(req);
  res.send({'message': 'Files received! k thnkx bye!'});
});

应该处理空文件上传。