How to convert local pdf to base64? - javascript

I have a local pdf file that I want to receive and convert to base64
import file from 'assets/PDFs/file.pdf';
const getBase64 = async (file) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
const fileURI = new File([file], 'file')
const base64Pdf = await getBase64(fileURI);
Finnaly, instead of a base64 file, I got a text file which contain a path to file assets/PDFs/file.pdf

For node environment:
import fs from 'fs'
try {
const data = fs.readFileSync('assets/PDFs/file.pdf', 'utf8')
const buff = new Buffer.from(data)
const base64pdf = 'data:application/pdf;base64,' + buff.toString('base64')
console.log(base64pdf)
} catch (err) {
console.error(err)
}
For browser environment:
const getBase64 = async(file) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
const file = document.querySelector("input").onchange = async(e) => {
let b64Data = await getBase64(e.target.files[0]);
console.log(b64Data)
}
<input type="file" accept=".pdf" />

Related

File uploader crashing for files larger than 300kb when using readAsDataURL on FileReader object

I am currently using the following method to convert files to base64 which crashes the browser(chrome) or abandons the job(firefox) when uploading larger files:
export const convertFilesToBase64: (
files: File[]
) => Promise<Base64FileObject[]> = async (files: File[]) => {
const toBase64 = async (file: File) =>
await new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => resolve(reader.result)
reader.onerror = (error) => reject(error)
})
if (files.length > 0) {
return await Promise.all(
files.map(async (file: File) => {
const database64 = (await toBase64(file)) as string
return {
filename: file.name,
url: URL.createObjectURL(file),
size: file.size,
dataBase64: database64.replace(/^data:.*\/.*,/, ''),
}
})
)
} else {
return []
}
}
Smaller files seem to work without any issues. It currently seems to fail on the reader.readAsDataURL(file) line. Not sure if I am missing something obvious here?

Convert fetch to axios

I did a 'get' with fetch but I want to do it with axios, could someone help me convert this code to axios?
detail: detail: I made the request to get an image, and I use the blob to be able to show this image to the user, and I would like to do that with axios as well.
Code:
const image = (url) =>
fetch(url)
.then((response) => {
return response.blob();
})
.then(
(blob) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
})
);
const image = async (url) =>
await axios.get(url)
.then(response => {
// can access blog directly from response...
}
Read more about axios here
Here: I am assuming this is a get request?
const image = async (url) => {
return await axios.get(url)
.then((response) => {
return response.blob();
})
.then(
(blob) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
})
);
}

blob to base64 conversion synchrorously in Javascript

I am calling a javascript function to initialize a variable value in Oracle Visual Builder (VBCS). The function takes the binary data as input and needs to return Base64 converted string synchronously so that the Base64 converted string is assigned to the VBCS variable.
The function does not return the Base64 converted string. How do I make it return the Base64 string to the calling function?
PageModule.prototype.convertbase64 = function (data) {
const blob = new Blob([data], {
type: "application/octet-stream"
});
function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => resolve(reader.result.toString().substr(reader.result.toString().indexOf(',') + 1));
reader.onerror = error => reject(error);
console.log(new Date());
});
};
const retstring = blobToBase64(blob).then(finalString => { return finalString });
console.log('retstring value', retstring);
return retstring;
};
The problem is in this line
const retstring = blobToBase64(blob).then(finalString => { return finalString });
You should wait for the result of blobToBase64 and make function convertbase64 async.
const retstring = await blobToBase64(blob);
Here is full example.
PageModule.prototype.convertbase64 = async function (data) {
const blob = new Blob([data], {
type: "application/octet-stream"
});
function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => resolve(reader.result.toString().substr(reader.result.toString().indexOf(',') + 1));
reader.onerror = error => reject(error);
console.log(new Date());
});
};
const retstring = await blobToBase64(blob);
console.log('retstring value', retstring);
return retstring;
};

How to return base64 data from a fetch promise?

I want to convert images from a URL to base 64, and store that in a state for later use.
How do I return the data from fetch()?
I can get it to work using CORS safe images and an HTML canvas, but this will not work for public domains.
openImage = (index) => {
const url = formatURLs[index];
const base64 = this.getBase64Image(url);
this.setState(prevState => ({
currentImage: index,
currentImagebase64: base64
}));
}
getBase64Image(url) {
fetch(url).then(r => r.blob()).then(blob => {
var reader = new FileReader();
reader.onload = function() {
var b64 = reader.result.replace(/^data:.+;base64,/, '');
return b64;
};
reader.readAsDataURL(blob);
});
}
When I console.log(reader.result), it will output base64 as expected.
However when I return b64, it returns to openImage as 'undefined'.
getBase64Image is async so when calling it in a sync way it will return undefined.
You can try something like that
openImage = async (index) => {
const url = formatURLs[index];
const base64 = await this.getBase64Image(url);
this.setState(prevState => ({
currentImage: index,
currentImagebase64: base64
}));
}
async getBase64Image(url) => {
const response = await fetch(url);
const blob = await response.blob();
const reader = new FileReader();
await new Promise((resolve, reject) => {
reader.onload = resolve;
reader.onerror = reject;
reader.readAsDataURL(blob);
});
return reader.result.replace(/^data:.+;base64,/, '')
}
You have to set state inside .then()
getBase64Image(url) {
fetch(url).then(r => r.blob()).then(blob => {
var reader = new FileReader();
reader.onload = function() {
var b64 = reader.result.replace(/^data:.+;base64,/, '');
this.setState({
currentImagebase64: b64
});
};
reader.readAsDataURL(blob);
});
}

Lag by taking an instance of an array using es6

I got an empty array while I'm logging for an instance of an array!
onSelectMultipleImage = (event): Promise<any> => {
return new Promise(resolve => {
const files = <File[]>event.target.files;
let file: File;
let counter = -1;
const response = [];
while (file = files[++counter]) {
const reader: FileReader = new FileReader();
reader.onload = ((f) => {
return () => {
response.push({
file: f,
base64: reader.result
})
}
})(file);
reader.readAsDataURL(file);
console.log(counter);
if(counter == files.length -1) {
console.log('inside the while');
resolve(response);
}
}
});
};
onImagesSelect = async (event: Event) => {
this.newImages = await this.helper.onSelectMultipleImage(event) || [];
console.log(this.newImages, "Original"); // [file: File, base64: "base 64 long string..."]
console.log([...this.newImages],"instance"); // [] empty array
setTimeout(() => {console.log([...this.newImages, 'instance'])}, 2000); // [file: File, base64: "base 64 long string..."]
}
So why I'm getting the presented result? It's something causing by the base64 presented inside the array? if yes what is the solution?
It doesn't wait reader.onload to be completed. So resolve(response) is called before response.push.
You can create a promise to read one file and return them with Promise.all like following code.
readFile = (file: File): Promise<any> => {
return new Promise(resolve => {
const reader: FileReader = new FileReader();
reader.onload = (f) => {
resolve({
file: f,
base64: reader.result
});
};
reader.readAsDataURL(file);
})
}
onSelectMultipleImage = (event): Promise<any> => {
const files = <File[]>event.target.files;
return Promise.all(files.map(file => readFile(file)));
};

Categories