Node Multer unexpected field

后端 未结 11 1527
情歌与酒
情歌与酒 2020-12-12 12:17

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

11条回答
  •  不思量自难忘°
    2020-12-12 12:56

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

提交回复
热议问题