NodeJS模块mutler:"错误:意外字段"再次

时间:2017-10-30 13:06:42

标签: node.js

我试图在学习nodejs的简单练习中使用mutler。上传文件后,获取" Unexpected归档"错误。我尝试了关于这个主题的所有内容,但我仍然无法摆脱这个错误。

这是我的node.js代码:

var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer  = require('multer');
var upload = multer({dest: 'tmp/'});
var type = upload.single('avatar');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', function (req, res) {
    res.sendFile( __dirname + "/" + "upload.html" );
})

app.post('/file_upload', type, async (req, res) => {
    console.log(req.file);
    })

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)
})

用于上传的html文件:

<html>
    <head>
       <title>File Uploading Form</title>
    </head>

    <body>
       <h3>Upload Profile:</h3>
       Select a file to upload: <br />

       <form action = "http://127.0.0.1:8081/file_upload" method = "POST" 
          enctype = "multipart/form-data">
          <input type="file" name="file" size="50" />
          <br />
          <input type = "submit" value = "Upload File" />
       </form>

    </body>
</html>

上传后我在网络浏览器中遇到的错误:

Error: Unexpected field
     at makeError (/home/mihai/nodejs/tutorial/node_modules/multer/lib/make-error.js:12:13)
     at wrappedFileFilter (/home/mihai/nodejs/tutorial/node_modules/multer/index.js:40:19)
     at Busboy.<anonymous> (/home/mihai/nodejs/tutorial/node_modules/multer/lib/make-middleware.js:114:7)
     at emitMany (events.js:146:13)
     at Busboy.emit (events.js:223:7)
     at Busboy.emit (/home/mihai/nodejs/tutorial/node_modules/busboy/lib/main.js:38:33)
     at PartStream.<anonymous> (/home/mihai/nodejs/tutorial/node_modules/busboy/lib/types/multipart.js:213:13)
     at emitOne (events.js:115:13)
     at PartStream.emit (events.js:210:7)
     at HeaderParser.<anonymous> (/home/mihai/nodejs/tutorial/node_modules/dicer/lib/Dicer.js:51:16)

有谁能告诉我如何让它发挥作用?我也试过Windows 7,节点v8.8.1并得到相同的错误。

1 个答案:

答案 0 :(得分:1)

该错误表示dist-package在请求中遇到了一个不期待的文件字段。

您已告诉multer期待一个名为multer的字段:

avatar

您的文件字段实际上称为var type = upload.single('avatar');

file

将其更改为<input type="file" name="file" size="50" /> ,一切正常:

avatar