I have some code(vanilla Javascript) that allows me to generate a Base64 string from an image and it works. I have to bring this string to node js and then store it in a MongoDB database. The problem is that once the fetch is done the string is undefined. What can I do?
Base64 encoder
var logoUri;
const file = logo.files[0];
if(file.size<=2e+6){
const reader = new FileReader
reader.addEventListener('load', ()=>{
// console.log(reader.result)
logoUri=reader.result
console.log(logoUri) // the console log works
//then i fetch (post) this logoUri
})
reader.readAsDataURL(file)
Related
I have following problem. I am saving image to local storage by converting it to string base 64 format via file reader.readAsDataUrl. it is stored properly. Now I want to send that image to the server. I am using fetch to fetch url and then blobing it to form a file. when i console.log i get same file as I got before converting to base 64 exept name is different. but when sending to the server that file object it returns unprocecable content. The image must be an image.
fr.readAsDataURL(value);
fr.addEventListener("load",() => {
// assigning freader value to state and refferencing it to `newVal`
// saving only happens inside `this` eventListener
try{
const newVal = generalInfo[iName][0] = fr.result;
// console.log(newVal)
setGeneralInfo({...generalInfo,newVal});
localStorage.setItem("generalP", JSON.stringify(generalInfo));
}
catch(e){
alert("photo sized more than 1mb cannot be uploaded");
// get back to current state values using LC
getFromLC();
}
})
and here is retrieving from local storage and turning it into file
const getSendingData = async () => {
//strip off the data uri prefix
// getting base64 string as data url
const response = await fetch(generalInfo.photo[0]);
const blob = await response.blob();
const file = new File([blob],'image',{type: blob.type});
// continue from here
console.log(file)
}
I want to extract the bytecode from an file I select (pdf) to save it in my database. But I am always getting the error that my byte is undefined. Could someone look at my code and tell me what is wrong with it?
I tried to use the FileReader but my byte returns undefined, the formdata works fine it shows on the console every information I need for the file.
EDIT:
uploadFile2(files: FileList | null): void {
const file = files.item(0)
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => {
this.documentsArray.push({documentType: this.form.controls.dokumentType.value, file: reader.result})
console.log(this.documentsArray)
}
}
Hi I edited my code and now I am getting a base64 I think, but one question, it starts like this:
data:application/pdf;base64,JVBERi0xLjQKJfbk/N8KM......."
is the start with data:application/pdf correct or do I have to change something to save it in the database
I'd suggest you to store the file as a base64 String in your database.
This would look as following. With the line number 2 you're fetching the file from your input event.
const reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onload = (event) => {
if (reader.result) {
//save pdf base64 into database
}
I successfully passed an image as binary string out of puppeteers page.evaluate() function back to node.js using:
async function getBinaryString(url) {
return new Promise(async (resolve, reject) => {
const reader = new FileReader();
const response = await window.fetch(url)
const data = await response.blob();
reader.readAsBinaryString(data);
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject('Error occurred while reading binary string');
});
}
I am able to save it with:
fs.writeFileSync(“image.png”, new Buffer.from(binaryString, "binary"), function (err) { });
But now I wish to convert this PNG image to base64 without saving it to file first because I will upload it to a different server. If I save it to file, I can do the following:
function base64Encode(file) {
const bitmap = fs.readFileSync(file);
return new Buffer.from(bitmap).toString('base64');
}
How do I skip the file saving part and get proper base64 data for my PNG?
I tried to pass binary string to new Buffer.from(binaryString).toString('base64') but I was unable to save it as a working PNG.
This doesn’t really warrant answering my own question but #Jacob reminded me that I forgot to try:
new Buffer.from(binaryString, 'binary').toString('base64');
with a "binary" parameter, which solved the issue and PNG was correctly formatted again when going from base64 to file or to image in a browser.
Maybe the code in question can be reused by some other puppeteer user, it took me a while to come up with and find pieces across the web.
I have been trying to convert an image file from my local machine but it seems not working for me.
I don't want to upload the image using an input because I'm only having the image path in production and i want to store the base64 string. but if there is a better way i can handle this then i don't mind
const reader = new FileReader();
const file = new File([imgUrl], { type: "image/png" });
console.log(file);
reader.addEventListener("load", function (e) {
console.log(e.currentTarget.result);
}, false);
const data = reader.readAsDataURL(file);
return data;
}
const img = "localhost:8080/start app abnner.png"; // my image path
getDataUrl(img);
The key is to use the result property of your object (see FileReader API.)
const reader = new FileReader()
reader.readAsDataURL(image) // assuming "image" is your file
reader.result // here is your base64 string
So in your case, it should be:
const data = reader.readAsDataURL(file);
return data.result;
I had to do something like this once, so I made a little plugin if you want: encode-image-uri. It has the advantage of using promises, so you’re 100% sure that you’re calling any function only when the conversion is done and your data is ready.
I'm trying to store images in DB2 Database as BLOB contents. I used JS to convert the image content to base64.
function loadImageFileAsURL()
{
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textAreaFileContents = document.getElementById
(
"textAreaFileContents"
);
textAreaFileContents.innerHTML = fileLoadedEvent.target.result;
var ImgContent = fileLoadedEvent.target.result;
$("#IMAGE").attr("src",ImgContent);
};
fileReader.readAsDataURL(fileToLoad);
}
}
Now I need to convert this base64 content to binary and store them to my DB2 Database. Is there any way to do this in JavaScript?
And how to fetch this data from the database and display it on my mobile app using Adapters. ?
Why do you not simply store the image as encoded to base64 in database? I think this would be better in your scenario...
You receive an image
You use some library to handle the encoding to base64
Review this question: Base64 encoding and decoding in client-side Javascript
You store the image-now a string, in the database
When you need to display the image in the app, fetch the contents and decode it (see step 2)