1

I have endpoint which is receiving files and need to send these files to 3rd party. However i'm not converting these files properly cuz i receive Invalid request format but if i read the file from fs the file is successfully deployed. How to create readStream from the input file? I tried Readable.from(file.buffer) still error. If i pass createReadStream(join(process.cwd(), 'images...')) is working as expected, here is the script.

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

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

  // Not working
  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}`);
  }
};

Andon Mitev
  • 1,354
  • 1
  • 11
  • 30
  • Does this answer your question? [Converting a Buffer into a ReadableStream in Node.js](https://stackoverflow.com/questions/13230487/converting-a-buffer-into-a-readablestream-in-node-js) – Molda Dec 13 '21 at 11:57
  • @Molda what is the img_string actually, this is the data that i'm receiving when image is uploaded: { fieldname: 'file', originalname: '245509749_237479131761955_2631090030549449386_n.jpeg', encoding: '7bit', mimetype: 'image/jpeg', buffer: , size: 61147 } – Andon Mitev Dec 13 '21 at 11:59
  • I have it here as part of the not working example: formData.append('file', Readable.from(file.buffer)); but still looks like different output than the createReadStream() – Andon Mitev Dec 13 '21 at 12:01
  • Try to turn the buffer into string before passing it to Readable. `formData.append('file', Readable.from(file.buffer.toString()));` That's what the 1st answer recommends. – Molda Dec 13 '21 at 13:38
  • 1
    @Molda thanks but even with ` formData.append('file', Readable.from(file.buffer.toString()));` still getting the error: Invalid request format :( – Andon Mitev Dec 13 '21 at 15:30

0 Answers0