在Express Node.js中将图像文件转换为base64 [英] Converting image-file into base64 in express nodejs

查看:163
本文介绍了在Express Node.js中将图像文件转换为base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to convert an image file into base64, so I can store in base64 string form in mongoDB.

这就是我要这样做的方式:

This is how I am trying to do that:

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:路径必须是字符串或缓冲区

TypeError: path must be a string or Buffer

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

how can I convert that image file(eg:image.jpg) into base64?

推荐答案

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

You will need to use Multer middleware to handle 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:请参阅下面的David评论.


2018-10-24: See David's comment below.

2019-06-11:修复了基于注释的示例.它确实是 req.file.buffer : https://github.com/expressjs/multer/blob/master/storage/memory.js#L8

2019-06-11: Fixed example based on comments. It is indeed req.file.buffer: https://github.com/expressjs/multer/blob/master/storage/memory.js#L8

这篇关于在Express Node.js中将图像文件转换为base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆