Upload and pin image with Piniata api on client side, no nodejs

Viewed 12

I am trying to use the Piniata api. Here it is: https://docs.pinata.cloud/

The idea is to upload and pin and image using the api, into my account in Piniata. I got this sample to upload a file in base64, using Node.js and server side. The sample use this api call: "https://api.pinata.cloud/pinning/pinFileToIPFS"

I am suppose to be able to do this in client side as well. However, there is no sample of client side without using Node.js. And I can't seem to find exactly a documentation of what the api call expects.

Here is the sample I got from the Piniata support:

const { Readable } = require("stream");
const FormData = require("form-data");
const axios = require("axios");

(async () => {
  try {
    const base64 = "BASE64 FILE STRING";
    const imgBuffer = Buffer.from(base64, "base64");

    const stream = Readable.from(imgBuffer);
    const data = new FormData();
    data.append('file', stream, {
          filepath: 'FILENAME.png'
  })

    const res = await axios.post("https://api.pinata.cloud/pinning/pinFileToIPFS", data, {
      maxBodyLength: "Infinity",
      headers: {
          'Content-Type': `multipart/form-data; boundary=${data._boundary}`,
          pinata_api_key: pinataApiKey,
          pinata_secret_api_key: pinataSecretApiKey
      }
    });

    console.log(res.data);
  } catch (error) {
    console.log(error);
  }
 })();

Here is my attempt to perform an upload from client side without Node.js

async function uploadFile(base64Data)
{

  const url = `https://api.pinata.cloud/pinning/pinFileToIPFS`;
  var status = 0;
  try {
      let data = new FormData();
      var fileName = "FILENAME.png";
      var file = new File([base64Data], fileName, {type: "image/png+base64"});

      data.append(`data`, file, file.name);
      data.append(`maxBodyLength`, "Infinity");

      const response = await postData('POST', url, {
        'Content-Type': `multipart/form-data; boundary=${data._boundary}`,
        "Authorization": "Bearer Redacted"
      },
      data
      );


  } catch (error) {
      console.log('error');
    console.log(error);
  }
}

What I get as a response from the server is 400 and the error being: {"error":"Invalid request format."}

What am I doing wrong? Also, it seems like when I try to use FormData .append with a stream as a sample, it doesn't work. As if it only expects a blob.

0 Answers
Related