Visitar URL original
how to upload multiple files with fields at once with formdata · Issue #559 · form-data/form-data · GitHub
Skip to content

how to upload multiple files with fields at once with formdata #559

Open

Description

@FlorentGrea

0

I have a pocketbase collection with "name", "image" and "order" fields. I'm trying to upload all the images with unique name and images using formdata at once.

here's some code:

`export default function AddPhotosAdmin({ photosDb }: PhotoDisplayProps) {
async function addPhotos(formData: FormData) {
'use server'

    const name = formData.get("name") as string
    let order = 0
    const dataPost = new FormData
    const Image_array = Array.from(formData.getAll("Image"))
    Image_array.map((image) => {
        dataPost.append('name', name)
        dataPost.append('Image', image)
        dataPost.append('order', (order++).toString())
    })
    const pb = new PocketBase(process.env.DB_ADDR);
    pb.collection('Photos').create(dataPost);
    revalidatePath("/Photos")
}
return (
    <div>
        <form action={addPhotos} className="text-black">
            <input name="name" />
            <input
                type="file"
                name="Image"
                required
                multiple
                accept="image/*"
                className="text-white"
            ></input>
            <input type="submit" className="text-white" value="Créer" />
        </form>
    </div>
)`

i tried a lot of ways to manage to send all the data at once, and using a loop POST is auto cancelled and seems not the good way to do it.

any ideas?

Activity

  1. formula1 commented on Oct 31, 2024

    @formula1

    You may have already solved your issue but have you tried something with Promise.all?

    async function addPhotos(formData: FormData) {
      const name = formData.get("name") as string
      let order = 0
      const dataPost = new FormData
      const Image_array = Array.from(formData.getAll("Image"))
    
      const pb = new PocketBase(process.env.DB_ADDR);
    
      await Promise.all(Image_array.map(async (image)=>{
        const imageBody = new FormData();
        imageBody.set('name', name)
        imageBody.set('Image', image)
        imageBody.set('order', (order++).toString())
        await pb.collection('Photos').create(imageBody);
      }))
    
      revalidatePath("/Photos")
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions