Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Update image

default discord avatar
onepoordeveloper8 months ago
4

Thanks man

  • default discord avatar
    mumincelal10 months ago

    Hello

    @1067378688569655296

    ,



    I saw somewhere but it was not definitely the documentation. I think, I saw it in someone's code.

  • default discord avatar
    onepoordeveloper11 months ago

    Hello

    @649859124284358656

    , I was facing a similar problem. My files were uploading fine but the alt text wasn't.


    This was my code


        const formData = new FormData()
        const filename = `${parseInt((Date.now() / 1000).toString())}`
        formData.append('file', dataURLtoFile(png, filename))
        formData.append('test', 'text')
    
        // formData.append('alt', 'test')
    
        try {
          const req = await fetch('/api/media', {
            method: 'POST',
            body: formData,
            credentials: 'include',
          })
          const data = await req.json()
          console.log('data', data)
          if (data.errors) {
            toast.error(data.errors[0].message)
            return
          }
          setValue(data.doc.url)
          toast.success('File uploaded to media')
        } catch (err) {
          console.log(err)
        }

    I noticed from your answer that your are using the key "_payload" while appending to formData. I used it like this and it worked. Thank you so much.



    My question is, how did you know about this? Is this something in documentation? I couldn't find any help around this except yours. Please guide..

  • default discord avatar
    mumincelallast year

    Yes, you can. If you write a code like below, I believe it will work for you.



    export const uploadMedia = async (
      token: string,
      imagePath: string,
      imageAlt: string,
      lang: LanguageCode
    ): Promise<UploadedMedia | undefined> => {
      const formData = new FormData();
      formData.append("_payload", JSON.stringify({ alt: imageAlt }));
      formData.append("file", fs.createReadStream(imagePath), {
        filename: uuidv4(),
      });
    
      try {
        const result = await axios.post(`${API_URL}/api/medias`, formData, {
          headers: {
            cookie: `payload-token=${token}`,
          },
          params: { locale: lang, "fallback-locale": null },
        });
    
        if (result.status !== 201) {
          throw new Error(result.statusText);
        }
    
        return result.data.doc;
      } catch (error) {
        // console.log("🚀 ~ file: utils.ts:248 ~ error:", `${imagePath} - ${error}`);
        if (error instanceof AxiosError) {
          throw error.response?.data;
        }
        throw error;
      }
    };
  • default discord avatar
    steproblast year

    Is it possible to update an image from Frontend using NEXTJS 13? I have my Company collection which is related to the Media collection.


    Or what is the right approach for this case?

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.