[英]Image to Base64 with NodeJS (Express)
我正在做测试,我需要将图像转换为 base64 以存储在我的数据库中
忘记数据库,我只需要 base64 作为字符串。
这是我的表格:
<form action="/cadastrado" method="POST">
<! -- other irrelevants inputs -->
<input type="file" name="input_file" id="input_file" onchange="converterParaBase64()" required><br>
<button type="submit" onclick="base64()">CADASTRAR</button>
</form>
这是我提交表单后的路线:
app.post("/cadastrado", (req, res) => {
const {input_nome, input_telefone, input_cpf, input_email, input_file} = req.body;
console.log(req);
return res.json({
nome: input_nome,
telefone: input_telefone,
cpf: input_cpf,
email: input_email,
// base64image: input_file.toBase64 (I need something like this)
});
});
我在使用字符串输入方面做得很好,例如 nome、telefone、cpf 和 email(PT-BR 中的变量)
但我不能对input_file
说同样的话
当我 console.log(req.body) 我得到这个:
{
input_nome: '1',
input_telefone: '2',
input_cpf: '3',
input_email: '4',
input_file: 'levia.jpg'
}
我需要将此 levia.png 图像转换为 base64 作为字符串。
我该怎么做?
更新 1:似乎 json 中的图像只是文件名。 可以在客户端和发送到服务器端之后进行转换吗?
尝试这个
var fs = require('fs');
app.post("/cadastrado", (req, res) => {
const {input_nome, input_telefone, input_cpf, input_email, input_file} = req.body;
console.log(req);
var bitmap = fs.readFileSync(input_file);
var base64File = new Buffer(bitmap).toString('base64');
return res.json({
nome: input_nome,
telefone: input_telefone,
cpf: input_cpf,
email: input_email,
base64image: base64File
});
});
所以我想出了如何解决我的问题。
有点替代我的所作所为。 不知道以后会不会出现问题,所以想和大家分享一下。
基本上我创建一个input
并在客户端编辑他的值。 当然,我不想要一个 Base64 代码搞乱我可怜的 HTML 的大输入,所以我用display: none
设置样式。 此输入在表单内,并发送到我的req.body
。
片段
index.html 页面格式:
...
<input type="file" id="input_file" name="input_file" onchange="convBase64()" required />
...
script.js 有一些逻辑
...
document.getElementById('input_base64').value = `${stringBase64}`;
...
css 用编码图像隐藏输入:
#input_base64 {
display: none;
}
这个不可见的输入在表单内部。 提交表单时,输入值将发送到请求正文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.