AdonisJS how can i store multi images with foreach

Viewed 26

I just started learning AdonisJS! i can store one image but now i want to store multi images and i can't find any example on AdonisJS how can i do that.

Now I'm saving image like this

   const imageSchema = schema.create({
      image: schema.file.optional({
        size: '2mb',
        extnames: ['jpg', 'png', 'gif'],
      }),
    })

    const validatedData = await ctx.request.validate({ schema: imageSchema })

    let tourDetailedImages: string | null = null
    const image = ctx.request.file('image')
    if (image) {
      const imageFileName = `tour-detailed-${validatedData.image?.size}.${image.extname}`
      await image.moveToDisk(`./`, {
        visibility: 'public',
        name: imageFileName,
      })
      tourDetailedImages = await Drive.getUrl(imageFileName)
    }
    const newImage: Partial<Image> = {
      ...validatedData,
      image: tourDetailedImages ?? '',
    }

    const storedImages = await Image.create(newImage)

How can i store 10 images in same time ? I think i need foreach here but don't really know how to use it can someone help me with this.

1 Answers

From the documentation:

When accepting multiple files from the same input, you can use the request.files method (the plural form) to return an array of the file instances.

import Route from '@ioc:Adonis/Core/Route'
import Application from '@ioc:Adonis/Core/Application'

Route.post('gallery', async ({ request }) => {
  const images = request.files('images')

  for (let image of images) {
    await image.move(Application.tmpPath('uploads'))
  }
})
Related