javascriptnode.jstypescriptapi

How to pass my createReadStream of an image file into a HTTP Post Request Body?


I'm writing a test that ensures my API does not allow files >10MB. And I need to pass an image into this API as a Post Request.

I believe I've figured out how I read the data from my image (If I log out assetSteam.on then I can see bytesRead is the correct size of my file = bytesRead: 16337697)

export async function uploadPhoto(filePath: string): Promise<any> {
  const assetStream = fs.createReadStream(filePath);
  assetStream.on('data', function (rawImageData) {
    return myPhoto.uploadImage(JSON.stringify(rawImageData));
  });
}

The argument passed into myPhoto.uploadImage is the body for the HTTP request.

I'm unsure as to how I pass this data to be read correctly as an image into my Post request body


Solution

  • I ended up going for a much simpler solution

      const imageData = fs.readFileSync(filePath, { encoding: 'base64' });
    

    Then passed stringified imageData into the body of my request.

    Worked a treat.