Search code examples
node.jstypescriptmultercloudinarydata-uri

converting image to base64 with data-uri with typescript


I successfully upload images with multer, store them in the local directory, save the path to the database. But since heroku does not save images in the local directory I have to upload images to Cloudinary but Cloudinary needs file to be converted to base64.

This is the implementation in node.js:

const path = require("path");
const DataUri = require("datauri");

const dUri = new DataUri();

exports.dataUri = (file: Express.Multer.File): string =>
  dUri.format(path.extname(file.originalname).toString(), file.buffer);

I tried to implement this in typescript like this:

import path from "path";
import DataUri from "datauri";
// here is cauinsg issue
const dUri = new DataUri();

export const dataUri = (file: Express.Multer.File): string =>
  dUri.format(path.extname(file.originalname).toString(), file.buffer);


in typescript implementation I am getting typescript error for const dUri = new DataUri() :

(alias) function DataUri(fileName: string, handler?: DataURI.Callback | undefined): Promise<string | undefined>

Expected 1-2 arguments, but got 0.ts(2554)
index.d.ts(2, 31): An argument for 'fileName' was not provided.
'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.

I dont understand why new DataUri() works in olain node but not in typescript. I thought it would be ts file error so ignored it but it did not work. When I start the app I got this error:" UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined"

Instead of creating function, I tried to implement like this in the controller:

 const image = req.file;
  const file64=new DataUri(image.buffer)

this did not work neither


Solution

  • here is my solution:

    import DatauriParser from "datauri/parser";
    const parser = new DatauriParser();
    

    Since I use multer and store the image to memory, I get req.file and req.file.buffer

     const extName = path.extname(req.file.originalname).toString();
      const file64 = parser.format(extName, req.file.buffer);
    

    Then

            const result = await Cloudinary.upload(file64.content!);