[英]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.