2

How to access text from request that are non-file fields? (I am using Insomia)

Our request using Insomia enter image description here

We are able to access file fields by looping through parts. using const parts = await req.files();.

index.js

    import Fastify from "fastify";
    import FastifyMultipart from "fastify-multipart";
    
    export const fastify = await Fastify();
    fastify.register(FastifyMultipart);

controllers/property.js

    export const addProperty = async function (req, res) {
      try {
        // WE ACCESS FILES OF MULTIPART FORM REQUEST HERE
        const parts = await req.files();
        for await (const data of parts) {
          console.log("*******File being access**********");
          console.log(data.filename); // access file name
          ...
        }
        // HOW DO WE ACCESS OTHER *NON_FILES* FIELDS?
        ...
        res.status(201).send({ message: "Property Added!." });
      } catch (error) {
        res.send(error);
      }
    };

in the controllers script we access files using await req.files();.

How do we access the fields that are non-file, like text

Evan
  • 2,327
  • 5
  • 31
  • 63

1 Answers1

8

There are two ways to get other data it is given in the docs https://github.com/fastify/fastify-multipart

  1. pass the other fields before file Passing the name before image

Now you can access name in data.fields

const data = await req.file();
console.log(data.fields.name.value); // virender
  1. you can attach it to body
fastify.register(require('fastify-multipart'), { attachFieldsToBody: true });
const file = req.body.image1;
const name = req.body.name.value
virender nehra
  • 470
  • 6
  • 12
  • FYI - for anyone interested - for option 2 - https://github.com/fastify/fastify-multipart#parse-all-fields-and-assign-them-to-the-body – userMod2 Aug 24 '23 at 04:10
  • And for option 1: `Note about data.fields: busboy consumes the multipart in serial order (stream). Therefore, the order of form fields is VERY IMPORTANT` – userMod2 Aug 24 '23 at 04:11