How to upload image file to media collection with Payload Handler?

default discord avatar
Nafisa Alam
8 months ago
2

my req.files have two files , image and payment slip. the api is a post api.both are images. i have a collection "media" where i upload all the images. now if i want to upload images to my media collection from a payload handler , how should i do that?


{image:
{name: 'quiz 1.png', data: Buffer(6520), size: 6520, encoding: '7bit', tempFilePath: '', …}
paymentSlip:
{name: 'images.jpeg', data: Buffer(11274), size: 11274, encoding: '7bit', tempFilePath: '', …}}
  • default discord avatar
    noheadphones
    8 months ago

    from the request you can pass the files directly into the media create function



    const media = await payload.create({
          collection: 'media',
          data: {
            alt: `My alt text`, // <- extra fields
          },
          file: req.files.file,
        })


    then you can update the reference/use of it in a content type if you need to



    const updatedContent = await payload.update({
            id: id,
            collection: 'content',
            data: {
              picture: media.id,
            },
          })


    in my example it's not an array though, so you'll need to change that for yours

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.