I have registration for in React where I need to upload files to the server. Those files needs to be Base64 encoded.
The function to encode it is as follows:
getBase64(file) {
let document = "";
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
document = reader.result;
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
return document;
}
And function to handle click on form's next button is as follow:
handleNextButtonClick(event){
event.preventDefault();
let data = {domainId: this.props.user[0].domainId, name: steps.stepThree, values: this.state.files};
let idCard = this.state.files.filter(file => file.file_type === "ID_CARD")[0].values.file;
let statuses = this.state.files.filter(file => file.file_type === "STATUTES")[0].values.file;
let blankLetterHead = this.state.files.filter(file => file.file_type === "LETTER_HEAD")[0].values.file;
let companyPhoto = this.state.files.filter(file => file.file_type === "COMPANY_PICTURE")[0].values.file;
let idCardBase64 = this.getBase64(idCard);
let statusesBase64 = this.getBase64(statuses);
let blankLetterHeadBase64 = this.getBase64(blankLetterHead);
let companyPhotoBase64 = this.getBase64(companyPhoto);
}
If I console log for example the first one this.state.files.filter(file => file.file_type === "ID_CARD")[0].values.file;
I get
Everything seems ok, but I'm getting error:
Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
Any idea how to solve this?
UPDATE
let idCardBase64 = idCard ? this.getBase64(idCard) : "";
let statusesBase64 = statuses ? this.getBase64(statuses) : "";
let blankLetterHeadBase64 = blankLetterHead ? this.getBase64(blankLetterHead) : "";
let companyPhotoBase64 = companyPhoto ? this.getBase64(companyPhoto) : "";
I changed it. And in this case exists only idCard
. Now I do not get any errors but idCardBase64
is ""
and not Base64 encoded.
Convert Files to Base64Just select your file or drag & drop it below, press the Convert to Base64 button, and you'll get a base64 string. Press a button – get base64. No ads, nonsense, or garbage. The input file can also be an mp3 or mp4.
file reading is asynchronous. so use callback or promise to solve your problem.
let idCardBase64 = '';
this.getBase64(idCard, (result) => {
idCardBase64 = result;
});
and use callback to return the data which you get.
getBase64(file, cb) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
cb(reader.result)
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With