node-formidable / formidable

The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.
MIT License
7k stars 680 forks source link

formidable doesn't return Data URI (base64 encoded) of file for cloudinary #872

Closed demosofa closed 1 year ago

demosofa commented 1 year ago

Support plan

Context

What are you trying to achieve or the steps to reproduce?

I try to upload the file uploaded to cloudinary by using formidable to get Data URI (base64 encoded) of file and then pass that data to first argument of cloudinary.uploader.upload(file: string). I thought I can use encoding property from formidable.Options in IncomingForm to make the files from callback of form.parse() return the file with data URI but I got empty {}. If I set encoding property at default "utf-8", the files will have file uploaded

import { IncomingForm, Fields, Files, Options } from "formidable";
import { NextApiRequest } from "next";

export default function parseForm(req: NextApiRequest, options: Partial<Options> = {
  multiples: true,
  keepExtensions: true,
  encoding: "base64"
}) {
  const form = new IncomingForm(options);
  return new Promise<{fields: Fields, files: Files}>((resolve, reject) => {
    form.parse(req, (error, fields, files) => {
      console.log(files)
      if (error) reject(error);
      resolve({ fields, files });
    });
  });
}

What was the result you got?

{}

What result did you expect?

an object from files that contain property to get data URI like multer package from Express.js

GrosSacASac commented 1 year ago

The encoding options is for receiving base64 files, it should not be used, it overrides transfer encoding of the one who sends file.

Use something like buf.toString('base64') on the file content to convert it to base64.

tunnckoCore commented 1 year ago

Use the VolatileFile (overriding the default writing to disk, with options.fileWriteStreamHandler) approach and convert its buffer with toString.

Soon it will be a lot easier, cuz Formidable will be more web-compliant with native File and FormData.

austencm commented 1 year ago

Hopefully this helps someone. Took me a while to figure it out.

import { IncomingForm } from 'formidable'
import { Writable } from 'stream'

let fileAsBase64 = ''

const form = new IncomingForm({
  fileWriteStreamHandler: () => {
    const writableStream = new Writable()

    writableStream._write = (chunk, encoding, next) => {
      fileAsBase64 += chunk.toString('base64')
      next()
    }

    return writableStream
  },
})