-1

I have file coming in request.file object. If I console.log(request.file) It prints

{
  fieldname: 'file',
  originalname: 'Screenshot from 2021-06-23 18-34-25.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: 'public/assets',
  filename: 'file-1628356843810.png',
  path: 'public/assets/file-1628356843810.png',
  size: 620962
}

Now I want to convert file to base64 string and I did

  const encoded = request.file?.buffer.toString("base64")
  console.log(encoded)

It says

TypeError: Cannot read property 'toString' of undefined
1

1 Answer 1

-3
const fs = require('fs');
// read binary data of the file
const binaryData = fs.readFileSync(request.file);
// convert binary data to base64 string
const base64String = new Buffer(binaryData).toString('base64');
5
  • 2
    Don't only post code as an answer but provide an explanation of what your code does and how it helps the OP.
    – Tyler2P
    Commented Aug 7, 2021 at 18:09
  • The code clearly had comments before each line.
    – Wai Ha Lee
    Commented Aug 8, 2021 at 4:39
  • Please see the comments. Commented Aug 8, 2021 at 11:58
  • 1
    This doesn't actually answer the question at hand. Please take some time to elaborate on your answer. Explain some things like how it solves the problem.
    – Taco
    Commented Aug 9, 2021 at 17:34
  • This answer in fact has nothing to do with the question...
    – H. Evers
    Commented Jan 6, 2024 at 14:05

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.