Can't send readable stream with Pinata SDK to IPFS - 400 bad request and Unhandled rejection

1.6k Views Asked by At

Due to the nature of my project I have a image dataURL (NOT an actual image file) that I am trying to upload to IPFS via Pinata SDK. I have converted the image dataURL into a buffer(array) and tried 2 different methods but none of them works. Here is my code:

SAMPLE 1

var myBlob = new Blob([new Uint8Array(myBuffer)]);
var myReadableStream = myBlob.stream()
pinata.pinFileToIPFS(myReadableStream)

ERROR: Unhandled Rejection (TypeError): source.on is not a function

SAMPLE 2

var myBlob = new Blob([new Uint8Array(myBuffer)]);

var myHeaders = new Headers();
myHeaders.append("pinata_api_key", "MY_KEY");
myHeaders.append("pinata_secret_api_key", "MY_SECRET_KEY");

var formdata = new FormData();
formdata.append("test", myBlob);

var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};

fetch("https://api.pinata.cloud/pinning/pinFileToIPFS", requestOptions)
.then(response => response.text())
.then(result => console.log('result',result))
.catch(error => console.log('error', error));

ERROR: 400 Bad Request, result {"error":"Unexpected field"}

1

There are 1 best solutions below

2
obo20 On

with buffers things can be a little tricky. You'll need to format your request in a slightly different way.

I would take a look at this code snippet for an example of how somebody got this to work:

const pinataSDK = require("@pinata/sdk");
const pinata = pinataSDK(
  "Pinata API Key",
  "Pinata API Secret"
);
const { fs, vol } = require("memfs");

(async () => {
  try {
    const base64 = "base64 file string";
    const buf = Buffer.from(base64, "base64");
    memfs.writeFileSync("File Name", buf);

    const read = vol.createReadStream("File Name");

    const res = await pinata.pinFileToIPFS(read);
    console.log(res);
  } catch (error) {
    console.log(error);
  }
})();