如何使用multer或body-parser上传文件 [英] How to upload file using multer or body-parser

查看:281
本文介绍了如何使用multer或body-parser上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名NodeJS初学者,跟随着使用MongoDB和NodeJS进行Web开发一书。我被困在第6章闷闷不乐。当我使用multer进行文件上传时,服务器会抛出以下错误:

I am a NodeJS beginner, following along a book "Web Development with MongoDB and NodeJS". I am stuck at its chapter 6 with 'multer'. When I use multer for file uploads the server throws the following error:

/Users/fk / Documents / imageuploader / node_modules / express / lib / application.js: 209
throw new TypeError('app.use() requires middleware functions'); ^

TypeError: app.use() requires middleware functions

但是当我将bodyParser替换为服务器,但是当我点击上传按钮时,它会在浏览器上显示以下错误。

but when I replace it with bodyParser the server fires up but when I click the upload button it gives me the following error on the browser.

500 TypeError: Cannot read property 'file' of undefined

然而,它应该将我重定向到另一个页面,显示上传的文件。

However, it is supposed to redirect me towards another page, where the uploaded file is shown.

这是我的bodyParser代码,请查看我是否正确使用它,因为它在服务器启动时给了我body-parser deprecated。我已经看到过像我这样的其他问题,但我遵循但没有一个真正起作用。

Here is my bodyParser code, please see if I am using it correctly because it gives me "body-parser deprecated" at the starting of the server. I've seen other questions like mine and I followed but none of them really work.

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(bodyParser({
  uploadDir: path.join(__dirname, '../public/upload/temp')
}));

以下代码显示我如何使用multer,以防万一我不应该做的事情请告诉我。如果上传文件,正文解析器或者multer,哪一个会更好?

Following code shows how I use multer, just in case if there is something I shouldn't be doing please let me know. Which one would be better in case of uploading files, body-parser or multer?

app.use(multer({
  dest: path.join(__dirname, '../public/upload/temp')
}));


var saveImage = function() {
  var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
    imgUrl = '';

  for (var i = 0; i < 6; i += 1) {
    imgUrl += possible.charAt(Math.floor(Math.random() * possible.length));
  }

  var tempPath = req.files.file.path,
    ext = path.extname(req.files.file.name).toLowerCase(),
    targetPath = path.resolve('./public/upload/' + imgUrl + ext);

  if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {
    fs.rename(tempPath, targetPath, function(err) {
      if (err) throw err;
      res.redirect('/images/' + imgUrl);
    });
  } else {
    fs.unlink(tempPath, function() {
      if (err) throw err;

      res.json(500, {
        error: 'Only image files are allowed.'
      });
    });
  }
};
saveImage();

前面的代码块是我用来上传文件的逻辑。在错误中,它将'file'称为undefined,它位于saveImage函数的以下行中。它无法获取路径,因此根据saveImage函数的else部分抛出错误500。为什么'file'在这里未定义?我不懂。

Preceding block of code is the logic that I am using to upload the file. In the error it is referring to 'file' as undefined which is in the following line in the saveImage function. It is unable to get the path and therefore throws error 500 according to the else part of the saveImage function. Why is 'file' undefined here? I dont get it.

var tempPath = req.files.file.path,


推荐答案

multer()返回使用您指定的设置的中间件生成器,因此您无法将其返回值直接传递给 app.use()。您可以在文档中查看它可以生成的所有类型的中间件,但通常会添加生成的中间件在路由级别而不是像其他身体解析器一样全局。这是因为您通常会传入您期望的文件字段的名称。

multer() returns a middleware generator that uses the settings you specified, so you cannot pass its return value directly to app.use(). You can see all of the types of middleware it can generate in the documentation, but typically the generated middleware are added at the route level instead of globally like the other body parsers. This is because you will typically pass in the name of the file field(s) that you will be expecting.

例如,这将接受单个文件(以及任何非文件字段)其表单字段名称为 foo

For example, this will accept a single file (along with any non-file fields) whose form field name is foo:

var upload = multer({
  dest: path.join(__dirname, '../public/upload/temp')
});

// ...

app.post('/upload', upload.single('foo'), function(req, res) {
  if (req.file) {
    console.dir(req.file);
    return res.end('Thank you for the file');
  }
  res.end('Missing file');
});

此外, body-parser 目前不在导出 multipart / form-data -capable中间件,因此您无法使用该模块处理上传的文件(嗯,不能在<$ c中传递base64编码的字符串$ c> application / x-www-form-urlencoded 表格或其他东西,但效率低得多。)

Also, body-parser does not currently export a multipart/form-data-capable middleware, so you cannot use that module for handling uploaded files (well, short of passing a base64-encoded string in an application/x-www-form-urlencoded form or something, but that's much less efficient).

这篇关于如何使用multer或body-parser上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆