Search code examples
node.jsmultipartform-datacontent-type

How to Post "multipart/form-data" Form and get the Text field values from the Node.js server?


Í'm trying to upload a file using multer. I can upload the file but somehow unable to get the text box values inside the form with the content/type "multipart/form-data".

<div class="container">
    <h1>File Upload</h1>
    <form action="/upload" method="POST" enctype="multipart/form-data" >
      <div class="file-field input-field">
        <div class="btn grey">
          <span>File</span>
          <input name="myImage" type="file" multiple="multiple"> 
        </div>
        <div class="file-path-wrapper">
          <input class="file-path validate" type="text">
        </div>        
      </div>
      <div ><input type="text" name="test"/></div>
      <button type="submit" class="btn">Submit</button>
    </form>
</div>

How can I get the value of the textbox

<div ><input type="text" name="test"/></div>

using body.parser? when I try

const {test} = req.body;

it gives an error TypeError: Cannot read property 'test' of undefined.


Solution

  • You need to include body parser to your node server:

    const bodyParser = require('body-parser');
    app.use(bodyParser.json());       
    app.use(bodyParser.urlencoded({ extended: true})); 
    

    Then you should have access to form data in body i.e. req.body.test.