Uploading a binary file buffer to Strapi using a custom Strapi Service

I'm working on a personal project that generates a web page screenshot (using Puppeteer) when a Strapi endpoint gets called.

After digging in the Strapi docs and archives, Stack Overflow, and deep in Google Search, I came up with only a couple of small leads.

Writing a Service in Strapi to handle the upload was the path I wanted to take; however, Strapi's documentation wasn't clear on using strapi.plugins.upload.services.upload.upload().

Based on what I could see, uploading a file to Strapi was primarily done by calling the upload endpoint. E.g. a file would be uploaded on the front end and sent via the endpoint to Strapi. I needed to upload a file generated on the server and use the upload Service within a Strapi Service.

When I tried using the Strapi upload Service directly with the binary buffer generated on the server, I ran into issues due to it expecting a file path that it can then read into a buffer:

readBuffer = await util.promisify(fs.readFile)(file.path);

This issue is resolved by skipping this step with a custom Service and providing Strapi with the binary buffer directly.

Here's the code that worked for me:

uploadFileBinary: async (binary, uuid) => {
    const fileInfo = { name : uuid }
    const metas = {}
    const { optimize } = strapi.plugins.upload.services['image-manipulation'];
    const { buffer, info } = await optimize(binary);
    const formattedFile = await strapi.plugins.upload.services.upload.formatFileInfo(
      {
        filename: uuid + '.png',
        type: 'image/png',
        size: binary.toString().length,
      },
      fileInfo,
      metas
    );
    const fileData = _.assign(formattedFile, info, {
      buffer,
    });
    const upload = await strapi.plugins.upload.services.upload.uploadFileAndPersist(fileData)
    return upload.id
}

Once implemented, I was able to call the endpoint and create the screenshot .png using Puppeteer and then provide the generated binary buffer to my custom uploadFileBinary Service to insert into Strapi's media library.

Success!

24