node.js 节点 Multer 意外字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31530200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node Multer unexpected field
提问by Sethe23
I'm working on uploading a file to my app using the multer npm module.
我正在使用 multer npm 模块将文件上传到我的应用程序。
The multer function I have defined is to allow a single file uploaded to the file system. Everything works during run time; the issue is after I upload the file I get an error below. Any advice appreciated on where to look.
我定义的 multer 函数是允许将单个文件上传到文件系统。在运行时一切正常;问题是在我上传文件后出现以下错误。任何关于在哪里看的建议表示赞赏。
Error:
错误:
Unexpected field
Error: Unexpected field
at makeError (c:\Users\Dev\WebstormProjects\Crunch\node_modules\multer\lib\make-error.js:12:13)
at wrappedFileFilter (c:\Users\Dev\WebstormProjects\Crunch\node_modules\multer\index.js:39:19)
at Busboy.<anonymous> (c:\Users\Dev\WebstormProjects\Crunch\node_modules\multer\lib\make-middleware.js:97:7)
at Busboy.emit (events.js:118:17)
at Busboy.emit (c:\Users\Dev\WebstormProjects\Crunch\node_modules\multer\node_modules\busboy\lib\main.js:31:35)
at PartStream.<anonymous> (c:\Users\Dev\WebstormProjects\Crunch\node_modules\multer\node_modules\busboy\lib\types\multipart.js:205:13)
at PartStream.emit (events.js:107:17)
at HeaderParser.<anonymous> (c:\Users\Dev\WebstormProjects\Crunch\node_modules\multer\node_modules\busboy\node_modules\dicer\lib\Dicer.js:51:16)
at HeaderParser.emit (events.js:107:17)
at HeaderParser._finish (c:\Users\Dev\WebstormProjects\Crunch\node_modules\multer\node_modules\busboy\node_modules\dicer\lib\HeaderParser.js:70:8)
app.js
应用程序.js
var multer = require('multer');
var app = express();
var fs = require('fs');
//. . .
var upload = multer({ dest: 'upload/'});
var type = upload.single('file');
app.post('/upload', type, function (req,res) {
var tmp_path = req.files.recfile.path;
var target_path = 'uploads/' + req.files.recfile.name;
fs.readFile(tmp_path, function(err, data)
{
fs.writeFile(target_path, data, function (err)
{
res.render('complete');
})
});
Index.hbs
索引.hbs
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name='recfile' placeholder="Select file"/>
<br/>
<button>Upload</button>
</form>
#Package.json
"dependencies": {
"body-parser": "~1.13.2",
"cookie-parser": "~1.3.5",
"debug": "~2.2.0",
"easy-zip": "0.0.4",
"express": "~4.13.1",
"hbs": "~3.1.0",
"less-middleware": "1.0.x",
"morgan": "~1.6.1",
"multer": "~1.0.0",
"serve-favicon": "~2.3.0"
}
}
采纳答案by stdob--
We have to make sure the type= file with name attribute should be same as the parameter name passed in
upload.single('attr')
我们必须确保带有 name 属性的 type= 文件应该与传入的参数名称相同
upload.single('attr')
var multer = require('multer');
var upload = multer({ dest: 'upload/'});
var fs = require('fs');
/** Permissible loading a single file,
the value of the attribute "name" in the form of "recfile". **/
var type = upload.single('recfile');
app.post('/upload', type, function (req,res) {
/** When using the "single"
data come in "req.file" regardless of the attribute "name". **/
var tmp_path = req.file.path;
/** The original name of the uploaded file
stored in the variable "originalname". **/
var target_path = 'uploads/' + req.file.originalname;
/** A better way to copy the uploaded file. **/
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(target_path);
src.pipe(dest);
src.on('end', function() { res.render('complete'); });
src.on('error', function(err) { res.render('error'); });
});
回答by vincent
The <NAME>you use in multer's upload.single(<NAME>)function must be the same as the one you use in <input type="file" name="<NAME>" ...>.
在<NAME>你multer的使用upload.single(<NAME>)功能必须是一样的,你在使用一个<input type="file" name="<NAME>" ...>。
So you need to change
所以你需要改变
var type = upload.single('file')
var type = upload.single('file')
to
到
var type = upload.single('recfile')
var type = upload.single('recfile')
in you app.js
在你 app.js
Hope this helps.
希望这可以帮助。
回答by Vince Banzon
A follow up to vincent's answer.
跟进文森特的回答。
Not a direct answer to the question since the question is using a form.
不是对问题的直接回答,因为问题是使用表格。
For me, it wasn't the name of the input tag that was used, but the name when appending the file to the formData.
对我来说,它不是使用的输入标签的名称,而是将文件附加到 formData 时的名称。
front end file
前端文件
var formData = new FormData();
formData.append('<NAME>',this.new_attachments)
web service file:
网络服务文件:
app.post('/upload', upload.single('<NAME>'),...
回答by siddharth ranjan
This for the Api you could use
这对于您可以使用的 Api
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
var multer = require('multer');
const port = 8000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(port, ()=>{
console.log('We are live on' + port);
});
var upload = multer({dest:'./upload/'});
app.post('/post', upload.single('file'), function(req, res) {
console.log(req.file);
res.send("file saved on server");
});
This also works fine used on Postman but the file doesn't comes with .jpg extension any Advice? As commented below
这也适用于 Postman,但该文件没有附带 .jpg 扩展名 任何建议?正如下面评论的
This is the default feature of multer if uploads file with no extension, however, provides you the the file object, using which you can update the extension of the file.
如果上传没有扩展名的文件,这是multer的默认功能,但是,为您提供文件对象,您可以使用它来更新文件的扩展名。
var filename = req.file.filename;
var mimetype = req.file.mimetype;
mimetype = mimetype.split("/");
var filetype = mimetype[1];
var old_file = configUploading.settings.rootPathTmp+filename;
var new_file = configUploading.settings.rootPathTmp+filename+'.'+filetype;
rname(old_file,new_file);
回答by Kapilrc
since 2 images are getting uploaded! one with file extension and other file without extension. to delete tmp_path (file without extension)
因为 2 张图片正在上传!一个带有文件扩展名,另一个文件没有扩展名。删除 tmp_path(没有扩展名的文件)
after src.pipe(dest);
后 src.pipe(dest);
add below code
添加下面的代码
fs.unlink(tmp_path); //deleting the tmp_path
fs.unlink(tmp_path); //deleting the tmp_path
回答by nobar
Unfortunately, the error message doesn't provide clear information about what the real problem is. For that, some debugging is required.
不幸的是,错误消息没有提供关于真正问题是什么的明确信息。为此,需要进行一些调试。
From the stack trace, here's the origin of the error in the multerpackage:
从堆栈跟踪中,这是multer包中错误的来源:
function wrappedFileFilter (req, file, cb) {
if ((filesLeft[file.fieldname] || 0) <= 0) {
return cb(makeError('LIMIT_UNEXPECTED_FILE', file.fieldname))
}
filesLeft[file.fieldname] -= 1
fileFilter(req, file, cb)
}
And the strange (possibly mistaken) translation applied here is the source of the message itself...
这里应用的奇怪(可能是错误的)翻译是消息本身的来源......
'LIMIT_UNEXPECTED_FILE': 'Unexpected field'
filesLeftis an object that contains the name of the field your server is expecting, and file.fieldnamecontains the name of the field provided by the client. The error is thrown when there is a mismatch between the field name provided by the client and the field name expected by the server.
filesLeft是一个对象,其中包含您的服务器期望file.fieldname的字段名称,并包含客户端提供的字段名称。当客户端提供的字段名称与服务器期望的字段名称不匹配时,会引发错误。
The solution is to change the name on either the client or the serverso that the two agree.
解决方案是更改客户端或服务器上的名称,使两者一致。
For example, when using fetchon the client...
例如,在fetch客户端上使用时...
var theinput = document.getElementById('myfileinput')
var data = new FormData()
data.append('myfile',theinput.files[0])
fetch( "/upload", { method:"POST", body:data } )
And the server would have a route such as the following...
并且服务器将具有如下所示的路由...
app.post('/upload', multer(multerConfig).single('myfile'),function(req, res){
res.sendStatus(200)
}
Notice that it is myfilewhich is the common name (in this example).
请注意,它是myfile通用名称(在本例中)。
回答by Ravi Singh
probably you are not giving the same name as you mentioned in the
upload.single('file').
可能您给出的名称与
upload.single('file').
回答by Felipe Santos
I solve this issues looking for the name that I passed on my request
我解决了这个问题,寻找我在请求中传递的名称
I was sending on body:
我正在发送身体:
{thumbbail: <myimg>}
and I was expect to:
我希望:
upload.single('thumbnail')
so, I fix the name that a send on request
所以,我修复了按要求发送的名称
回答by MonoThreaded
In my scenario this was happening because I renamed a parameter in swagger.yamlbut did not reload the docs page.
Hence I was trying the API with an unexpected input parameter.
Long story short, F5is my friend.
在我的场景中,这是因为我重命名了一个参数,swagger.yaml但没有重新加载文档页面。
因此,我正在尝试使用意外输入参数的 API。
长话短说,F5是我的朋友。

