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

};`

Top comments (0)