【问题标题】:How to convert request file to base64 string in nodejs如何在nodejs中将请求文件转换为base64字符串
【发布时间】:2021-10-12 03:00:07
【问题描述】:

我有文件进入 request.file 对象。如果我console.log(request.file) 它打印

{
  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
}

现在我想将文件转换为 base64 字符串,我做到了

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

它说

TypeError: Cannot read property 'toString' of undefined

【问题讨论】:

标签: javascript node.js base64 multer image-upload


【解决方案1】:
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');

【讨论】:

  • 不要只发布代码作为答案,还要解释代码的作用以及它如何帮助 OP。
  • 代码每行前明显有cmets。
  • 请看cmets。
  • 这实际上并没有回答手头的问题。请花一些时间来详细说明您的答案。解释一些事情,例如如何解决问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
相关资源
最近更新 更多