DEV Community

ZahidRahman47
ZahidRahman47

Posted on

uploading file into pinata

hello family. in this function i want to send multiple png,s to pinata using their file upload system and then i want to fetch the images and map it inside my react app here is my code please some one let me know if they already face this issue .

`const handleImageChange = async () => {
setLoaderThree(true);
try {
const formData = new FormData();
const files = Array.from(selectedFile);

  files.forEach((file) => {
    console.log(file.name);
    formData.append("file", file);
    formData.append(
      "pinataMetadata",
      JSON.stringify({
        name: file.name,
      })
    );
  });

  formData.append(
    "pinataOptions",
    JSON.stringify({
      cidVersion: 0,
    })
  );

  const res = await fetch(
    "https://api.pinata.cloud/pinning/pinFileToIPFS",
    {
      method: "POST",
      headers: {
        pinata_api_key: `${apikey}`,
        pinata_secret_api_key: `${secretapikey}`,
      },
      body: formData,
    }
  );

  if (res.ok) {
    const resData = await res.json();
    console.log("Parent Hash:", resData.IpfsHash);
    const filesResponse = await fetch(
      `https://gateway.pinata.cloud/ipfs/${resData.IpfsHash}`
    );
    if (filesResponse.ok) {
      const filesText = await filesResponse.text();
      console.log("Response Body:", filesText);
      // Push each image with its corresponding metadata
      files.forEach((file, index) => {
        setImagesWithMetadata((prev) => [
          ...prev,
          { imageUrl: filesText, metadata: { name: file.name } },
        ]);
      });
    } else {
      console.error(
        "Failed to retrieve files within the parent hash:",
        filesResponse.statusText
      );
    }
  } else {
    console.error("Failed to pin the file to IPFS");
  }

  setLoaderThree(false);
} catch (error) {
  console.error("Error while processing response:", error);
  setLoaderThree(false);
}
Enter fullscreen mode Exit fullscreen mode

};`

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay