2

I'm using pinata and trying to pin some files to ipfs. These files are coming from user input and not readed from the fs. Having this code:

export const deployFile = async (
  file: Express.Multer.File,
  httpService: HttpService,
): Promise<string> => {
  const formData = new FormData();

  formData.append('file', Readable.from(file.buffer));

  try {
    const observable = httpService
      .post(process.env.PINATA_BASE_URL + '/pinning/pinFileToIPFS', formData, {
        headers: {
          'Content-Type': `multipart/form-data; boundary=${formData.getBoundary()}`,
          pinata_api_key: process.env.PINATA_API_KEY,
          pinata_secret_api_key: process.env.PINATA_API_SECRET_KEY,
        },
      })
      .pipe(map((response) => response.data));

    const response = await lastValueFrom(observable);

    return response.IpfsHash;
  } catch (error) {
    logger.error(`Error deploying image reason: ${error.response.data.error}`);
  }

Always hitting error Invalid request format.. How ever if file is readed from the fs using:

const formData = new FormData();

formData.append('file', createReadStream(join(process.cwd(), '/images/1.jpeg')));

Everything work as expected and file is successfully pinned on Pinata. So i'm thinking: Readable.from(file.buffer) is different than createReadStream(join(process.cwd(), '/images/1.jpeg')) Any idea how to deploy user files directly to ipfs and not reading them from FS?

2 Answers 2

0

If you don't want to use Pinata API, then it's a straightforward way to do it from the node.js side 💪

👇👇👇

async function storeImages(imagesDirPath) {
  const fullImagesPath = path.resolve(imagesDirPath);
  const files = fs.readdirSync(fullImagesPath);
  let responses = [];
  console.log("Uploading to Pinata !!!");
  console.log("paths ", fs.createReadStream(fullImagesPath + "/" + files[0]));
  for (fileIndex in files) {
    const readableStreamForFile = fs.createReadStream(
      `${fullImagesPath}/${files[fileIndex]}`
    );
    try {
      const response = await pinata.pinFileToIPFS(readableStreamForFile);
      responses.push(response);
    } catch (error) {
      console.log(error);
    }
  }
  return { responses, files };
}
async function storeTokeUriMetadata(metadata) {
  try {
    const response = await pinata.pinJSONToIPFS(metadata);
    return response;
  } catch (error) {
    console.log(error);
  }
  return null;
}

Good luck 👍👍👍

0

Here is an example how to use `

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);
  }
})();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.