I have a postgres database where I store images in a bytea type field. When I convert an image to base 64 with C# and serialize it with NewtonSoft then it saves it and then I query and display it perfect. However trying to do the same with javascript as the way to serialize the image is different. How do I get it to be the same format? The javascript code I have is this:
carga.addEventListener('click', async (e) => {
e.preventDefault();
if (selectedFile) {
let fileReader = new FileReader();
let blob=new Blob([selectedFile]);
fileReader.readAsDataURL(blob);
fileReader.onload = async(event) => {
let data = event.target.result;
console.log(btoa(data));
let idNen= JSON.parse(localStorage.getItem('idNegocio'));
var raw = JSON.stringify({
"Id": idNen[0].id,
"Data":btoa(data)
});
await crearImagen(raw);
}
} else {
this.mostrarMensaje(`No se pudo reconocer la imagen. Por favor revise los datos`, `error`);
}
});
async function crearImagen(raw) {
try {
modal.style.display = 'block';
efect.style.display = 'block';
var myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${this.token}`);
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
await fetch(`${this.url}/api/imagenes`, requestOptions)
.then(response => response.text())
.then(result =>
{
console.log(result);
this.mostrarMensaje(`Imagen registrada exitosamente!`, `success`);
})
.catch(error => console.log('error', error));
} catch (error) {
this.mostrarMensaje(error, `error`);
}
modal.style.display = 'none';
efect.style.display = 'none';
}
The c# code that works is this:
string ruta = @"C:\Users\Administrator\Pictures\nod.png";
var bites= File.ReadAllBytes(ruta);
var base64=Convert.ToBase64String(bites);
var anonimo = new {titulo="test",data=base64 };
string json = JsonConvert.SerializeObject(anonimo,Formatting.Indented);
The format with .NET of the base64 in the serialized json that works is this:
"data": "/9j/4AAQSkZJRgABAQAAAQABAAD/ ......
and the format that javascript creates for me is something like this:
"data": "ZGF0YTphcHBsaWNhdGlvbi9vY3RldC1zdHJlYW07YmFzZTY0LGlWQk9SdzBLR2dvQUF
As you can see, it is different and when I consult the image in that format, the image is not displayed correctly.
Based on an answer given in this link: https://stackoverflow.com/questions/57534783/how-to-reconstruct-audio-blob-from-a-base64-encoded-string . I was able to find a solution to my problem because the FileReader's readAsDataURL() method already converts the image to base64, however it contains some headers that must be removed to keep only the encoded part. I removed the headers as follows:
With this I was able to store the image in the database and use it like the ones I save from C#.