Multer error unexpected field

Hello, i've tried to upload a file with postman, but i get an "MulterError: Unexpected field", i search in all issues and i see all the time this is the field name. But for me i put t...

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

zoukie33 opened this issue

Nov 30, 2018

· 34 comments


Closed

MulterError: Unexpected field

#690

zoukie33 opened this issue

Nov 30, 2018

· 34 comments

Comments

@zoukie33

Hello,
i’ve tried to upload a file with postman, but i get an «MulterError: Unexpected field», i search in all issues and i see all the time this is the field name. But for me i put the good filedname in postman and in my code.

here my code (sorry for screens, my first time posting code in issues):

image

here my postman request:
shitappend

Thank your for the help.

Potional, mtahir08, hbsoftco, Himanshusinghofficial, mdaijaj, ofuochi, bandaranaike, MrHmP, ProgrammingHero1, LyesAtt, and 3 more reacted with thumbs up emoji
Potional, mdaijaj, apeksha7777, and TNKKung reacted with heart emoji

@LinusU

It does indeed look right, I’m sorry that you are having trouble with this.

Could you try and log the name of the unexpected field (this should probably be part of the message btw. happy to take a pull request for that). You can do that by adding this error handler to express and observing the output in the terminal:

app.use(function (err, req, res, next) {
  console.log('This is the invalid field ->', err.field)
  next(err)
})

@zoukie33

hello again,
i’ve done what you told me, and i get: «This is the invalid field -> pic».
but the file field in postman is goo and in the code too.

field_error

Phuonglv123, vadim-givola, aditodkar, hbsoftco, surfiend, pragsjain, jayasurya-mkm, bandaranaike, hangupwd, Al1st1c, and 2 more reacted with thumbs up emoji
aditodkar, muhammadsarim555, and chuhoanglong reacted with heart emoji

@LinusU

Hmm, interesting 🤔

Could it be that there is more than one muter attached as a middleware somehow? It’s hard for me to tell since I can’t see the entire code…

That’s the only thing I can think of, otherwise, could you try and reduce this to the absolute minimal code that’s required to show this behavior and upload somewhere, and then I could take a look at it 👀

@zoukie33

Could it be that there is more than one muter attached as a middleware somehow? It’s hard for me to tell since I can’t see the entire code…

hum i dont really know, but i have jwt protection for this routes, and i have an invalid Access if i dont put this in my app.js :

app.use(upload.array());
app.use(express.static('public'));
app.use('/files', express.static('files'));

I’ve tried without upload.array(), not working and with .none() the same.
this in my app.js can be the problem, but without that i can’t access to the route.

for now i just uploaded the 3 files concerned about this problem, if you want i can make you a working version without all my routes (because if you run my api without everything behind this won’t work ^^).

here the files
https://ufile.io/c3yp2

my app is working on ubuntu server: Ubuntu 18.04.1 LTS

@LinusU

This line is probably the problem, it shouldn’t be there as it will catch all files uploaded to any route and then complain that that they have the wrong field (since none was supplied to that function).

wachukxs, beita1, rubenjr0, MrxC0d3r, ankurgupta255, isais1, lazycipher, funkybunch, AlejandroAldana99, tom-leamon, and 5 more reacted with thumbs up emoji
tom-leamon, BukkyOmo, IsabelVillafuerte, milanvthakor, and julesntare reacted with heart emoji

@zoukie33

ok, so what can i do to fix that ? cause if i dont put it in my add.js, and post route who need an upload cant be reach if this is not here …
the solution can be do an app.use on multer + the configurations needed (storage etc), but how can i use it next in multiples routes ?

@LinusU

You should be able to remove the app.use(upload.array()) but keep the , upload.single('pic'), part. Is there anything that doesn’t work when you do that?

@zoukie33

I’ve already try it, it i remove the app.use(upload.array()), there is a conflic with my jwt securrity, i have an error 401 (Invalid Access). All the routes who need an auth pass through this function:

var verifyToken=function (req, res,next) {
	var token = req.body.token || req.query.token || req.headers['token'];
	 if (token) {
		jwt.verify(token, config.secret, function (err, currUser) {
			if (err) {
				res.send(err);
			} else {
				req.currUser = currUser;
				next();
			}
		});
	}
	 else {
		res.status(401).send("Invalid Access");
		console.log("User rejeté");
	}
};

but as you can see, in postman there is the token. did i need to put multer bnefore jwt auth ? It’s not very safe in my case … :/

@LinusU

ah, hmmm, is there a specific reason for providing the token in the body instead of as a header?

Specifically, it’s best practice to name the header Authorization and add the token as Bearer ${token}

@zoukie33

I will try, I will come back to you as soon as possible

@wachukxs

This line is probably the problem, it shouldn’t be there as it will catch all files uploaded to any route and then complain that that they have the wrong field (since none was supplied to that function).

fixed the problem. Thanks a whole lot @LinusU

@bogadrian

Let me help here if I can. I had same problem. 2 hours to understand the error. When I was sending the Postamn field as photo, I had there some space after inserting photo in form-data name field. so multer was returning the error every time as it wasn’t able to match photo (some white space) with upload.single(‘photo’) in my code. I solved this by changing the name from photo in only p, in Postamn and in my app upload.single(‘p’) Too stupid error but so hard to detect.

Marvel-Ib, shloimimink, MichelCassol, grangerjs, matheus1987, cartman1978, Vergil333, Sharon-Liu-go, paulurbina, web-developer032, and 8 more reacted with thumbs up emoji
xitter and mohmmadmoussa1988 reacted with thumbs down emoji
shloimimink, itsaareez1, jeevakalaiselvam, and GhassenBoughzala reacted with laugh emoji
ODAncona and nitatemic reacted with hooray emoji
wilson-faustino, divee789, IMMANUEL5015, adjeteyboy, Marvel-Ib, AnuragAgarwal00, matheus1987, cartman1978, Vergil333, jeevakalaiselvam, and 3 more reacted with heart emoji

@wilson-faustino

I was having the same error message.

In my case the problem was that I was using «upload.single(‘productImage’)» in Node JS and in Postman I was using ‘prodImg’ inside the file field.

I changed the file field name to ‘productImage’ so that would match «upload.single(‘productImage’)».

Now I get no more error messages.

@jonchurch

Closing as original thread went inactive. This is a common error, if you experience it yourself try some of these solutions and if you you’re still stuck you’ll get more visibility opening a new issue ❤️

@cvallejoec

This worked for me. I also add the field name in my component.ts
public uploader:FileUploader = new FileUploader({ url: 'http://localhost:3000/api/upload', itemAlias: 'yourFieldName', });

@jrschumacher

I had to change my usage of upload.array('files') to upload.array('files[]')

marekswiecznik, yelper, grallm, TanyaDolgopolova, EnesUcar1, daviddyess, xTCry, lukasbee1, songz, and jobafash reacted with thumbs up emoji
grallm, josenriagu, and xTCry reacted with heart emoji

@webafra

i same problem.
if create two file input for upload ( thumbnail and gallery input ) but send three file ( avatar or any other input name ) , give this error !

this method is not resolve if send correct input name ( thumbnail or gallery )
(err, req, res, next)

this method give error after send not send correct input name :
(req, res, next)

!!!!!

please help me.

@jrschumacher

@webafra have you tried the approaches listed above? For instance my comment on Apr 12.

@webafra

@webafra have you tried the approaches listed above? For instance my comment on Apr 12.

No, my inputs are different.
For example, I send a picture to Avatar and a PDF file.
In this case, Malter makes a mistake and does not allow the process to continue.

@jrschumacher

@webafra Please create a codesandbox.io example showing your issue. There is no way to assist you based on your description.

@osadasami

I got the same issue and solve it. Your input name should me the same as upload.single('inputName')

<input id="inputfield" type="file" name="upfile">
app.post('/api/fileanalyse', upload.single("upfile"), (req, res) => { 
  res.json({
    "name": req.file.originalname,
    "type": req.file.mimetype,
    "size": req.file.size
  })
})

@kuldeepchopradotnet

I was also getting this error then i did this step

just removed this
app.use(upload.array());
or put this line after registering all routes

image

@mdaijaj

i have same issue how can be solve please tell me if you know i am stucking whole day.

app.post(‘/upload’, (req,res)=>{
upload(req, res, err =>{
if(err){
console.log(err)
}else{
console.log(req.file)
}
})

@Julix91

@mdaijaj Stuck the whole day and can’t be bothered to format the question?

Check out some of the answers above, such as #690 (comment)

@isais1

This line is probably the problem, it shouldn’t be there as it will catch all files uploaded to any route and then complain that that they have the wrong field (since none was supplied to that function).

Thanks!

@nikhils4

If anyone wants to upload multiple files using multer and getting unexpected field error, try replacing upload.array('image') to upload.any('image').

@tatianajiselle

Thanks @osadasami -> knowing the field name is the same as the upload.single('inputName') saved me!

@Chanondler

I had to change my usage of upload.array('files') to upload.array('files[]')
@jrschumacher
Doesn’t work in my case.
uploadImage.array('photos', 10),
or
uploadImage.array('photos[]', 10),

Screenshot 2020-10-30 at 4 00 48 PM

@lazycipher

This line is probably the problem, it shouldn’t be there as it will catch all files uploaded to any route and then complain that that they have the wrong field (since none was supplied to that function).

It saved my day! didn’t help directly but I knew what to look for after that i.e overridden config!!
Thanks a ton!

@guidorearte

`router.post("/", upload.single("**avatar**"), async (req, res) => {
  try {
    // Upload image to cloudinary
    const result = await cloudinary.uploader.upload(req.file.path);
// Create new user
let user = new User({
  name: req.body.name,
  **avatar**: result.secure_url,`

Look for the parameter avatar of the first line with the object user is avatar too!

@Maximization

@julesntare

This line is probably the problem, it shouldn’t be there as it will catch all files uploaded to any route and then complain that that they have the wrong field (since none was supplied to that function).

Ewana aha urandokoye musaza

@Dmaina5054

@Davidon4

I encountered this error after 24hours of headache and fixing and scattering my code and was finally able to solve this, I discovered that multer stopped working with newer versions of some packaging, Mine was with express-jwt (with the newer version not taking function as the middleware) so what i did was install the older version and voila it worked for me.

Содержание

  1. Fix «Unexpected field» Error From Multer
  2. Input name needs to match multer function argument
  3. With FormData
  4. Inputs with multiple files might have a name ending with []
  5. Finding the unexpected field
  6. Other possible causes
  7. Conflicting multer instances
  8. Unaccounted file inputs
  9. Number of files exceeding the configured limit
  10. Conclusion
  11. How do you upload a file in Node.js?
  12. ES Modules in Node.js
  13. Set up Automated Deployments From Github With Webhook
  14. Unclear error message «MulterError: Unexpected field» #799
  15. Comments
  16. Reproduce
  17. Mailgun
  18. Error
  19. Footer

Fix «Unexpected field» Error From Multer

You set out to implement file uploads in Node.js, only to get blocked by this particular error:

MulterError: Unexpected field

What does this cryptic message even mean?!

By now you’ve already spent several hours trying to solve this problem. Why does implementing a simple file upload feature have to be so hard?!

It doesn’t have to be this way though. Writing an endpoint that accepts, parses and uploads a file in Node.js can be straightforward.

After reading this article, you’ll turn an annoying error into something you’ll solve in less than 5 minutes!

Read on or if you prefer video, watch it below.

Input name needs to match multer function argument

The foremost cause for this error is when the name attribute of the file input doesn’t match the argument passed to one of multer’s middleware functions.

Input name needs to match with the argument in multer middleware function

The NAME you use in multer’s upload.single(NAME) middleware function (or any of the other functions discussed below) must be the same as the name attribute of the input element .

Therefore, you have to double-check that these values are an exact match. Pay extra attention to invisible whitespace or characters that may look the same but have a different Unicode value. It’s better to copy-paste the value from one place to another.

Multer is strict in what input it accepts from the client, and for a good reason. File uploads can be a big vulnerability for backend servers. It’s easy for a bad actor to overflow the server with a huge amount of files, or send malformed data that breaks the parser and potentially gives the hacker access to the server. Multer is designed with a mindset to trust nothing that comes from the client so it can protect your server from a potential DoS attack.

Depending on the form data you’re expecting from the client, multer provides you with different middleware functions:

  • no file (text only) — upload.none()
  • single file — upload.single(fieldname)
  • multiple files, single input — upload.array(fieldname[, maxCount])
  • multiples files, multiple inputs — upload.fields(fields) where fields is an array of objects with name and optionally maxCount keys
  • any of the above — upload.any() (avoid if possible)

multer.any() is oftentimes used as a quick fix. This is dangerous and can make your server vulnerable to attacks. multer.any() will accept all files sent by the client which can lead to unexpected values further down in your application logic. Especially when used as a global middleware instead of a route-specific middleware.

It’s always better to fix the error by making sure field names are the same, instead of using multer.any() .

If you decide to use multer.any() , use it only on specific routes and make sure you’re handling all uploaded files.

Use the appropriate middleware function so that the form data received from the client is allowed to pass through. When you see an «Unexpected field» error from Multer, it’s because the middleware function is rejecting some (or all) form data.

With FormData

When you’re using FormData to programatically construct a form, input name is the first argument to the .append() function:

You then have to make sure that the same value, NAME in this case, is used as the fieldname argument in the middleware function:

Inputs with multiple files might have a name ending with []

In some cases, you might have a client that appends [] to the input name if it has multiple files.

When you configure multer to accept a photos field but the client sends photos[] instead, multer will throw a MulterError: Unexpected field error.

To fix the error, append [] to the fieldname argument in the middleware function: upload.array(‘photos[]’) .

Finding the unexpected field

Error messages from multer are rather cryptic. They don’t give you much information to help you find the root cause of the problem.

There’s a way to extract a little bit more information from the error thrown by multer and find the rejected field.

Add an error handling middleware and log the error argument. More specifically, the field property of the error tells you which input name multer has an issue with:

In a Node.js production application, you’d want to replace console.log with a proper logging mechanism to avoid messy logs and quickly find what you’re looking for.

Having found the rejected field, you’re a step closer to solving the error since you know where to start looking.

Other possible causes

If the error persists after verifying the input name matches the multer function argument, there might be something else going on. Here are three other possible causes for this error, and a solution for each.

Conflicting multer instances

I’ve seen this come up a few times so it’s worth mentioning.

Make sure there is only one multer instance used in the middleware chain of any particular route.

What do I mean by this? Let’s look at an example:

Can you see what’s wrong with the above example?

There’s a multer instance used on all routes ( upload.array() ) and another multer instance ( upload.single(‘photo’) ) specific to the /upload route.

If you try to upload a single file with the correct input name ( photo ), the first multer instance will throw an error and the code never reaches the second multer instance. That’s because upload.array() is missing a fieldname argument and it will always throw an error on file uploads.

If you’re using multer at top of your middleware chain to get access to the authentication token in the body, you should move it to the request headers instead. It’s standard practice to put an authentication token in the Authorization header.

Unaccounted file inputs

Remember when I said earlier that multer is strict about accepting form data from the client?

Even if you made sure the field names are the same, you will still face this error if there are file inputs you haven’t told multer about.

You can configure multer to accept multiple fields with the upload.fields(fields) method. fields is an array of objects with a name , and optionally maxCount , key.

For example, the following HTML form has two file inputs:

To configure multer to accept the above form, you would have to write the following code:

This configuration tells multer we’re expecting two file input fields named «avatar» and «photos» with no more than 1 and 6 files, respectively. In case there are other fields present, multer will throw an «Unexpected field» error.

Number of files exceeding the configured limit

When you see a MulterError: Unexpected field error, you don’t suspect the reason to be the number of files exceeding the configured limit.

If you’re using a middleware function that allows multiple files to be uploaded ( .array() or .fields() ), make sure the number of files uploaded doesn’t exceed the maxCount value.

To quickly check if this might be the cause, set maxCount to a huge number (eg.: upload.array(‘photos’, 9999) ). If the error disappears, you’ve found the issue. Either increase maxCount to allow more files to be uploaded at once, or change the client to send fewer files at a time.

Conclusion

Fixing cryptic multer errors and getting file uploads to work properly in Node.js can be a frustrating experience.

The foremost reason for the «Unexpected field» error is when the file input name doesn’t match the argument passed to the multer function.

Other possible reasons for this error are conflicting multer instances, unaccounted file inputs and exceeding the number of files limit.

How do you upload a file in Node.js?

Use this FREE request parsing guide and implement seamless working Node.js APIs that follow the latest best practices.

No spam! 🙅🏻‍♀️ Unsubscribe at any time.

You Might Also Like

ES Modules in Node.js

5 min read

Set up Automated Deployments From Github With Webhook

7 min read

Источник

Unclear error message «MulterError: Unexpected field» #799

With multer, you can basically allow/expect one, multiple, none or any attachments.

When you send an attachment to an endpoint that doesn’t accept one, you get the cryptic error message: «MulterError: Unexpected field».

Wondering if there is a critical problem and checking all my form fields for possible illegal characters, changing field names, etc, it turns out an attachment was sent but not expected.

I think the error message should be: Unexpected Attachment or Attachment Forbidden.

Reproduce

Exposed over serveo for testing purposes.

Mailgun

Sending a test request with this button

Error

Lines 38 to 45 in 805170c

function wrappedFileFilter ( req , file , cb ) <
if ( ( filesLeft [ file . fieldname ] || 0 ) 0 ) <
return cb ( new MulterError ( ‘LIMIT_UNEXPECTED_FILE’ , file . fieldname ) )
>
filesLeft [ file . fieldname ] -= 1
fileFilter ( req , file , cb )
>

Alternatively the request just continue with the decoded form parameters, ignoring the unexpected attachments.

The text was updated successfully, but these errors were encountered:

@Redsandro I was able to reproduce the issue,
When the server encounters unexpected file error is returned to multer-error.js

return cb ( new MulterError ( ‘LIMIT_UNEXPECTED_FILE’ , file . fieldname ) )

In multer-error.js error mapping is defined, where ‘LIMIT_UNEXPECTED_FILE’ error is mapped to Unexpected field.

‘LIMIT_UNEXPECTED_FILE’ : ‘Unexpected field’

For the request just continue with the decoded form parameters, ignoring the unexpected attachments, currently it is not supported.
Let me know if this helps in clearing your doubts.

@HarshithaKP thank you. I understand why this happens now.

The error message is still ambiguous. Could be helpful to others to clarify it.

‘File not allowed in form-data with this method. Use «.any()» in stead.’

I’m having this error message and cannot decode the thread.

What could I have done to receive the error «MulterError: Unexpected field»?

What is it expecting instead?

@ogrotten this error message is ambiguous, and you could have probably figured it out on your own if the message was a bit less abstract.

I’m not sure what you are starting with, but every option has a set amount of accepted files.

Multer function Files accepted n
multer.none()
multer.any() 0+ n
multer.single() 1 1
multer.array() 1+ >=1
multer.fields() 1+ >=1

So you probably either used .none() and submitted a file, or .single() and submitted more than one file.

Without knowing what you’re trying to do, the safest bet is probably to use .any() .

Hope this helps.

@Redsandro interesting . . . I used single() and only had one file, but I think the sent object may not have named the fields the way multer was expecting.

I appreciate the post tho. It basically means that if I come this way again, I’ll likely use .any() «just in case».

@Redsandro I am getting this error when posting a form without a file while using single() . Does that mean single() has to have at least one file?

@Redsandro how can I configure it to accept 0 or a maximum of 1 file? The same route handles single file uploads as well as forms without any files. hence sometimes a form has 1 upload and sometimes 0.

I think you can’t. Either submit the form to a different handler based on whether or not a file was selected client-side, or accept any() .

But this isn’t my project. Maybe a maintainer or developer of this expressjs plugin can be of more help.

@Redsandro @aysiscore To my understanding, that isn’t the case.

When using single and sending a form without a file input field, or even an empty file input field, this error won’t be triggered (assuming that if a file input field is present at all, there is only one and it named how single is expecting it to be).

See this bare bones example codesandbox. Click «Upload image» without selecting one. The error won’t be triggered.

@aysiscore We’d need to see your upload route and how you’re submitting the form from the client to better understand what the issue is. Feel free to open another issue.

Hello all, I’m a newbie in node-express, my requirement is to upload multiple images at once. So on Postman, I have images[] , and then I tried using upload.array(‘name’) , didn’t work. What works indeed is the upload.any() .

Hello everyone! I want to also mention that the same error happens when the «name» attribute in the file upload

is not the same as in the
upload.single(«X»)

@ilyes42 Thanks man, Totally missed that

that the same error happens when the «nam

Yes sir, That was my error!! Thanks Man!

I had the same problem and then it is resolved when I changed the destination folder name. Check if your uploading file name and destination folder name are the same. If they are change the destination folder name.

I am facing this problem. How can I achieve something like this?

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

I’m working on uploading a file to my app using the multer npm module.

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.

Error:

Unexpected field

Error: Unexpected field
    at makeError (c:UsersDevWebstormProjectsCrunchnode_modulesmulterlibmake-error.js:12:13)
    at wrappedFileFilter (c:UsersDevWebstormProjectsCrunchnode_modulesmulterindex.js:39:19)
    at Busboy.<anonymous> (c:UsersDevWebstormProjectsCrunchnode_modulesmulterlibmake-middleware.js:97:7)
    at Busboy.emit (events.js:118:17)
    at Busboy.emit (c:UsersDevWebstormProjectsCrunchnode_modulesmulternode_modulesbusboylibmain.js:31:35)
    at PartStream.<anonymous> (c:UsersDevWebstormProjectsCrunchnode_modulesmulternode_modulesbusboylibtypesmultipart.js:205:13)
    at PartStream.emit (events.js:107:17)
    at HeaderParser.<anonymous> (c:UsersDevWebstormProjectsCrunchnode_modulesmulternode_modulesbusboynode_modulesdicerlibDicer.js:51:16)
    at HeaderParser.emit (events.js:107:17)
    at HeaderParser._finish (c:UsersDevWebstormProjectsCrunchnode_modulesmulternode_modulesbusboynode_modulesdicerlibHeaderParser.js:70:8) 

app.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

<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"
  }
}
1) Solution

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>" ...>.

So you need to change

var type = upload.single('file')

to

var type = upload.single('recfile')

in you app.js

2) Solution

We have to make sure the type= file with name attribute should be same
as the parameter name passed in 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'); });

});
3) Solution

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.

front end file

   var formData = new FormData();
   formData.append('<NAME>',this.new_attachments)

web service file:

   app.post('/upload', upload.single('<NAME>'),...
4) Solution

This for the Api you could use

 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

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.

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);
5) Solution

Different file name which posted as «recfile» at <input type="file" name='recfile' placeholder="Select file"/> and received as «file» at upload.single('file')

Solution : make sure both sent and received file are similar upload.single('recfile')

6) Solution

since 2 images are getting uploaded! one with file extension and other file without extension.
to delete tmp_path (file without extension)

after
src.pipe(dest);

add below code

fs.unlink(tmp_path); //deleting the tmp_path

7) Solution

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

8) Solution

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 multer package:

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'

filesLeft is an object that contains the name of the field your server is expecting, and file.fieldname contains 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.

The solution is to change the name on either the client or the server so that the two agree.

For example, when using fetch on the client…

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 myfile which is the common name (in this example).

9) Solution

In my case, I had 2 forms in differents views and differents router files. The first router used the name field with view one and its file name was «inputGroupFile02». The second view had another name for file input. For some reason Multer not allows you set differents name in different views, so I dicided to use same name for the file input in both views.

enter image description here

10) Solution

In my scenario this was happening because I renamed a parameter in swagger.yaml but did not reload the docs page.

Hence I was trying the API with an unexpected input parameter.
Long story short, F5 is my friend.

11) Solution

probably you are not giving the same name as you mentioned in the
upload.single('file') .

12) Solution

Instead of using the name attribute of the input, use the key you are using to pass the file.

Example: My FormData Object:

Client Side:

formData.append('file', fileBlob);

Server Side:

multer.single('file');

Comments Section

Would you mind explaining why this works and what’s different? —_____—

Works perfectly like charm.We have to make sure the type= file with name attribute should be same as the parameter name passed in upload.single(‘attr’)

Mine case it’s not working. I am facing same issue. But in my windows machine code is working. I am having issues with my MAC.? Can anyone help with me this?

The name attribute of the type=»file» in html should match the upload.single(‘name’) in server code.

It would help if they put this in the readme instead of filling it with ‘avatar’.

But we still need to avoid the exception in case of misuse.. how to catch this exception?

How to set the client request for a multiple files upload? The ‘files’ field is empty.

Just for reference, if you’re using curl, and the command looks like this:curl -v -F [email protected]/myfile.txt localhost:3000/upload (http://localhost:3000/upload) Then the value for upload.single is «upload»

This saved my day. Thank you. If you use FormData.append() the name attribut from the <input> tag will be overwritten and makes the other solutions not working.

This answer is so important and incredibly helpful. Making sure that the formData key name is the same as the upload key argument is crucial. It works for me now.

Thank you so much. Your comment gave me a hint about my error. In my case, I had 2 forms in differents views and differents router files. The first router used the name field with view one and its file name was «imgLoading». The second view had another name the file input. For some reason multer not allows you set differentes name in different views, so I dicided used same name for the file input in both views.

This helped a lot.

Saved a lot of debugging time. God bless you.

Thank you very much. It helped me a lot, saved my day

Related Topics
node.js
multer

Mentions
Brent Bradburn
Anye
Ravi Singh
Vincent
Thamaraiselvam
Ugali Soft
Mono Threaded
Vince Banzon
Stdob
Kapilrc
Felipe Santos
Siddharth Ranjan
Luis Armando
Hariom Sinha

References
31530200/node-multer-unexpected-field

I’m setting up a server to upload zip files from the client. The server runs with express and multer to do this. When uploading a file, the server throws a «MulterError: Unexpected field» error and I cannot figuere out what is cousing it.

I’ve tried with png images and It works just fine. But with the zip files it just doesn’t work.

const multerConfig = {
    //specify diskStorage (another option is memory)
    storage: multer.diskStorage({
      //specify destination
      destination: function(req, file, next){
        next(null, './public/zip-storage');
      },

      //specify the filename to be unique
      filename: function(req, file, next){
        console.log(file);
        const ext = file.mimetype.split('/')[1];
        //set the file fieldname to a unique name containing the original name, current datetime and the extension.
        next(null, file.fieldname + '-' + Date.now() + '.'+ext);
      }
    }),

    // filter out and prevent non-image files.
    fileFilter: function(req, file, next){
          if(!file){
            next();
          }
        // only permit zip mimetypes
        const zip = file.mimetype.startsWith('application');
        if(zip){
          console.log('zip uploaded');
          next(null, true);
        }else{
          console.log("file not supported")
          errorReq = true;
          return next();
        }
    }
  };


  /* ROUTES
  **********/
  app.get('/', function(req, res){
    res.render('index.html');
  });

  var errorDetection = function(){
    if(!errorReq){
      errorReq = false;
      return('complete.html');
    } else{
      errorReq = false;
      return('errorupload.html');
    }
  }

  app.post('/upload', multer(multerConfig).single('photo'),function(req, res){
      //Here is where I could add functions to then get the url of the new photo
      //And relocate that to a cloud storage solution with a callback containing its new url
      //then ideally loading that into your database solution.   Use case - user uploading an avatar...
      res.redirect('complete.html');
  }

);

  // RUN SERVER
  app.listen(port,function(){
    console.log(`Server listening on port ${port}`);
  });

This is the error:

MulterError: Unexpected field
    at wrappedFileFilter (/home/axentiva-miguel/Documentos/ServerAPP/node_modules/multer/index.js:40:19)
    at Busboy.<anonymous> (/home/axentiva-miguel/Documentos/ServerAPP/node_modules/multer/lib/make-middleware.js:114:7)
    at emitMany (events.js:147:13)
    at Busboy.emit (events.js:224:7)
    at Busboy.emit (/home/axentiva-miguel/Documentos/ServerAPP/node_modules/busboy/lib/main.js:38:33)
    at PartStream.<anonymous> (/home/axentiva-miguel/Documentos/ServerAPP/node_modules/busboy/lib/types/multipart.js:213:13)
    at emitOne (events.js:116:13)
    at PartStream.emit (events.js:211:7)
    at HeaderParser.<anonymous> (/home/axentiva-miguel/Documentos/ServerAPP/node_modules/dicer/lib/Dicer.js:51:16)
    at emitOne (events.js:116:13)

Понравилась статья? Поделить с друзьями:
  • Multer error enoent no such file or directory open
  • Mui autocomplete error
  • Msdn error codes
  • Mugen как изменить портрет
  • Mugen как изменить картинку