繁体   English   中英

在express nodejs中将图像文件转换为base64

[英]Converting image-file into base64 in express nodejs

我正在尝试将图像文件转换为 base64,因此我可以将 base64 字符串形式存储在 mongoDB 中。

这就是我试图做到这一点的方式:

router.post('/file_upload',function(req,res){

  function base64_encode(file) {
    var bitmap = fs.readFileSync(file);
    return new Buffer(bitmap).toString('base64');
}

  var ImageFileToSave =  base64_encode(req.body.file);

  console.log(ImageFileToSave);


})

在客户端:

<form action="/file_upload" method="POST" enctype="multipart/form-
 data">
<input type="file" name="file" />
<input type="submit" value="Upload File" />
</form>

这是我得到的错误

TypeError:路径必须是字符串或缓冲区

如何将该图像文件(例如:image.jpg)转换为 base64?

您将需要使用Multer中间件来处理multipart/form-data

const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()

app.post('/file_upload', upload.single('example'), (req, res, next) => {
  // req.file is the `example` file or whatever you have on the `name` attribute: <input type="file" name="example" />
  // I believe it is a `Buffer` object.
  const encoded = req.file.buffer.toString('base64')
  console.log(encoded)
})

2018-10-24:见下面大卫的评论。

2019-06-11:基于评论的固定示例。 它确实是req.file.bufferhttps : //github.com/expressjs/multer/blob/master/storage/memory.js#L8

由于之前的答案对我不起作用,我正在分享另一个有效的答案。 我使用multer库获取文件然后将其转换为base64

const multer  = require('multer')
const upload = multer({});

router.post('/uploadlogo', upload.single('logo'), (req, res, next) => {
    // encoded has the base64 of your file
    const encoded = req.file.buffer.toString('base64');
});

如果您想要更多控制权,您也可以通过某种方式手动执行此操作。 这是一个示例,但您可以以任何您想要的方式实现它,作为中间件或作为 function 单独调用。

这是假设您的图像是 base64,即“req.body.image”。


var ImageMiddleware =  (req, res, next)=> {
  if (req.body.image && req.body.foldername && req.body.filename){
    const imagepath = req.body.foldername + "/" + uuidv4() + "_" + req.body.filename;

      function buff(data) {
        const base64 = data.split(',')[1];
        let buff = Buffer.from(base64, 'base64');
        return buff
      }

      fs.writeFileSync(imagepath, buff(req.body.image))

  }
}


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM