Node.js把前台传来的 base64 码转成图片
最近项目有个功能,更换用户个人头像,裁剪后上传保存。裁剪用了cropper.js
,裁剪后的图片为base64
编码格式,传到node
中,进行转换成图片在保存到数据库中,代码如下:
const express = require("express");
const router = express.Router();
const fs = require('fs-extra')
const path = require("path");
router.post('/topng', (req, res, next) => {
let { imgUrl } = req.body;
if (imgUrl) {
const fileName = Date.now() + '.png';
const base64 = imgUrl.replace(/^data:image\/\w+;base64,/, "");//去掉图片base64码前面部分data:image/png;base64
const dataBuffer = Buffer.from(base64,'base64'); //把base64码转成buffer对象,
let pwd = path.join(__dirname, `../img.png`);
fs.outputFile(pwd, dataBuffer, { overwrite: true }, function (err) {//用fs写入文件
if (err) {
console.log(err);
res.json({ result: false, code: 500, message: "图片文件上传失败!" });
} else {
res.json({ result: true, code: 200 });
}
})
} else {
res.json({ result: false, code: 500, message: "上传内容不能为空!" });
}
});
module.exports = router;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
上次更新: 2024/01/30, 00:35:17
- 01
- Node与GLIBC_2.27不兼容解决方案08-19
- 02
- Git清空本地文件跟踪缓存08-13