Lordrauf
Lordrauf

Reputation: 101

Node Express upload file with additional data

I am new to Node JS want to create Rest API for Upload Image and facing this issue.

I want to create a post method with multiple files and additional data from inputs. This is my code:

index.js :

app.post('/upload-photos', upload.array('photos'), function (req, res) {
  const uploadInfo = req.files.map(file => {
    return {
      sourceName: file.originalname,
      newName: file.filename
    };
  });
  res.send(uploadInfo);
});

My issue is I want to add some form data like (name, address, phone), has anyone else experienced this, please help me.

Thanks.

Upvotes: 2

Views: 1137

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40434

When using multer additional fields can be accessed through req.body.

app.post('/upload-photos', upload.array('photos'), function (req, res) {
  const { name, address, phone } = req.body;

  const uploadInfo = req.files.map(file => {
    return {
      sourceName: file.originalname,
      newName: file.filename
    };
  });
  res.send(uploadInfo);
});

In your form:

<form action="/upload-photos" method="post" enctype="multipart/form-data">
  <input type="file" name="photos" multiple />
  <input type="text" name="name" />
  <input type="text" name="address" />
  <input type="text" name="phone" />
</form>

Upvotes: 2

Related Questions