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;
};
Related
I am using FileReader in typescript to convert a blob to a base64 image that will then be displayed in the template of my application.
adaptResultToBase64(res: Blob): string {
let imageToDisplay : string | ArrayBuffer | null = '';
const reader = new FileReader();
reader.onloadend = function () {
imageToDisplay = reader.result;
return imageToDisplay;
};
reader.readAsDataURL(res);
return imageToDisplay;
}
Whilst the data logged inside the read.onloadend function displays the base64 string I cannot pass it out of the function.
I have tried adding a callback but where it is called elsewhere doesn't return anything but an empty string.
Please check this code
<input type="file" id="file">
<button id="click">click</button>
let data: string | ArrayBuffer;
document.getElementById('file').onchange = function (e: Event) {
let files: FileList | null = (<HTMLInputElement>e.target).files;
let reader: FileReader = new FileReader();
reader.onload = function (e: ProgressEvent<FileReader>) {
console.log(e.target.result);
data = e.target.result;
};
if (files.length > 0) {
reader.readAsDataURL(files?.[0]);
}
};
document.getElementById('click').onclick = function () {
console.log(data); // result if present otherwise null is returned
};
Using a separate method view. The return value is a Promise.
function adaptResultToBase64(res: Blob): Promise<string> {
let reader: FileReader = new FileReader();
return new Promise((resolve, reject) => {
reader.onloadend = () => {
resolve(reader.result as string);
}
reader.onerror = () => {
reject("Error reading file.");
}
reader.readAsDataURL(res);
})
}
To get the result
adaptResultToBase64(/* Blob value */)
.then(resp => console.log(resp))
.catch(error => console.log(error));
See here for specifics on Promise
MDN
learn.javascript.ru
The basic result I needed and did not realise that the reader.onload is actually a callback for read.readAsDataUrl and finishes everything inside it async.
adaptResultToBase64(res:Blob){
const reader = new FileReader();
reader.onload = function () {
// Was missing code here that needed to be called asynchronously.
adapterToNewObject(reader.result.toString())
};
reader.readAsDataURL(res);
}
}
I was performing this in Angular so for anyone else who runs into this problem here it is using Angular syntax:
In your class:
export class Component {
adaptedResult:Result
getBase64() {
this.http.get().subscribe((result: Blob) => {
const reader = new FileReader();
reader.onload = () => {
this.adaptedResult = this.adapter(reader.result) // Assign or use reader.result value, this is an example of using an adapter function.
};
reader.readAsDataURL(result);
});
}
adapter(base64:string){
return {
name:'image',
image:base64'
}
}
}
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" />
I have a working code to convert my File object to base64:
let reader = new FileReader();
reader.readAsDataURL(myFile);
reader.onload = () => {
let resultStrOrArrayBuf = reader.result;
if (!(resultStrOrArrayBuf instanceof ArrayBuffer)) {
..do something with resultStrOrArrayBuf
}
};
However I do now have to integrate this part to an existing rxjs chain. In the chain I receive the File object and would like to go on with the base64 result of the conversion. However the conversion is done with the help of the onload event. Is there some way to convert this event to a new observable and pass this to the chain?
there is no out of the box method to convert this loaded event to rxjs observable. you will have to make your own operator.
export const dataUrlToObs = myFile => new Observable<string | ArrayBuffer>(subscriber => {
const reader = new FileReader();
reader.readAsDataURL(myFile);
reader.onload = () => {subscriber.next(reader.result); subscriber.complete(); };
reader.onerror = () => subscriber.error(reader.error);
return () => reader.abort(); // cancel function in case you unsubscribe from the obs
}
it later can be used like this:
..chain
switchMap(myFile => dataUrlToObs(myFile)),
tap(resultStrOrArrayBuf => {
if (!(resultStrOrArrayBuf instanceof ArrayBuffer)) {
..do something with resultStrOrArrayBuf
}
})
Consider the following helper function, which accepts a Blob as a parameter and return an Observable<string>:
function blobToBase64(blob: Blob): Observable<string> {
return new Observable<string>(observer => {
const reader = new FileReader();
reader.onerror = observer.error;
reader.onabort = observer.error;
reader.onload = () => observer.next(reader.result as string);
reader.onloadend = observer.complete;
reader.readAsDataURL(blob);
return {
unsubscribe: reader.abort
}
})
}
Usage:
declare const fileObservable: Observable<File>;
fileObservable
.pipe(switchMap(blobToBase64))
.subscribe(base64 => console.log(base64))
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);
});
}
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)));
};