Node.js处理Base64格式图片方法及Buffer()弃用警告解决方案
问题解答
Node.js是否内置Base64编码能力?
Node.js原生内置了Base64编解码能力,基于内置的Buffer模块实现,无需引入任何第三方依赖即可直接使用。
报错原因与修复方案
你遇到的废弃警告触发原因是new Buffer()构造函数已经被官方废弃,该API存在安全风险和可用性缺陷,官方推荐使用Buffer.from()、Buffer.alloc()等替代API处理Buffer创建逻辑。
同时你的代码还存在两处会导致运行失败的问题:
- 变量拼写错误:
descodedImg.data拼写错误,实际定义的变量名为decodedImg - 文件写入逻辑错误:一是路径拼接缺少分隔符,会导致文件无法写入到uploads目录;二是写入二进制图片文件不能指定
utf8编码,会导致图片损坏。
修正后的完整代码
const uploadimage = asyncHandler(async(req, res, next) => { try{ var matches = req.body.base64image.match(/^data:([A-Za-z-+/]+);base64,(.+)$/); const response = {}; if(matches.length !== 3){ return new Error('Invalid input string'); } response.type = matches[1]; // 替换废弃的new Buffer为Buffer.from response.data = Buffer.from(matches[2], 'base64'); let decodedImg = response; // 修正拼写错误 let imageBuffer = decodedImg.data; let type = decodedImg.type; let extension = mime.extension(type); let fileName = "image." + extension; // 修正路径拼接和编码参数错误 fs.writeFileSync(`uploads/${fileName}`, imageBuffer); return res.send({ "status":"success" }) }catch(e){ return res.send({ "status":"failed", }) } });
内容的提问来源于stack exchange,提问作者Ali hassan
相关产品推荐
相关产品推荐

