How to post array of files using json? axios

Viewed 30

I write react, typescript project with Axios. And I need to send an array of images to the server. Can I post them using JSON rather than FormData? When I set the array named images, I get the following files on the server:

enter image description here

And when I try to get the array named images, I get undefined. Is there any method to post a file array using JSON?

My post request:

export const createProduct = async (product: IProductCreate) => {
  const { data } = await $authHost.post<IProductCreate>('api/product', product, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  return data
}

await createProduct({
      description,
      price,
      gender: JSON.stringify(gender),
      images: images,
      Colors: JSON.stringify(colors),
      BrandId,
      CategoryId
    })

On the server side, I use express with sequelize and typescript.

async create (req: productCreateRequest, res: Response, next: NextFunction): Promise<void> {
    try {
      ...
      if (!req.files) return next(ApiError.internal('Images are not uploaded'))
      const { images } = req.files // get images.0, images.1, images.2 (for each element or an file array)

      const fileNames: string[] = []
      if (Array.isArray(images)) {
        images.forEach((el, index) => {
          fileNames[index] = uuidv4() + '.png'
          el.mv(path.resolve('src/static/' + fileNames[index]))
        })
      } else {
        fileNames[0] = uuidv4() + '.png'
        images.mv(path.resolve('src/static/' + fileNames[0]))
      }

      const product = await Product.create({
        CategoryId,
        BrandId,
        price,
        description,
        gender: JSON.stringify(parsedGender),
        images: JSON.stringify(fileNames)
      })

      res.json(product)
    } catch (error) {
      ...
    }
  }
1 Answers

You can try to convert the files into binary and send them. Apply method like below for each file

images.0.data.toString('binary')
Related