converting audio file to base64 using javascript - javascript

I want to convert audio file into base64 using Javascript only.
We can convert images into base64 using canvas. But how can we convert audio files.
Any help will be grateful.

you can give the below code a try, it uses btoa
function getData(audioFile, callback) {
var reader = new FileReader();
reader.onload = function(event) {
var data = event.target.result.split(',')
, decodedImageData = btoa(data[1]); // the actual conversion of data from binary to base64 format
callback(decodedImageData);
};
reader.readAsDataURL(audioFile);
}

Here's how to convert an audio file to a base64 string with JavaScript:
async function audioToBase64(audioFile) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onerror = reject;
reader.onload = (e) => resolve(e.target.result);
reader.readAsDataURL(audioFile);
});
}
You can use it like this:
<input oninput="audioToBase64(this.files[0]).then(result => console.log(result))" type="file">
This will console.log a string like data:audio/mpeg;base64,//uYxAAAAA... when a file is chosen in that filepicker.

Related

Excel binary data to fileReader

I have a binary string (from an REST API) that is the content of a Excel file.
PK\x03\x04\x14\x00\x06\00\x00\x00���N�0\x10E�H�C�-#\b5��\x12*Q>�ēƪc[�ii����\x10B�\x15j7�\x12��{2��h�nm���ƻR\f����U^\x1B7/���%�\x17\x19�rZY�\x14\x1B#1\x19__�f�\x00�q��R4D�AJ�\x1Ah\x15\x16>����V\x11�ƹ\f�Z�9����NV ...
What I want is to put this content in a FileReader object. I tried to convert the content to blob and to use readAsBinaryString but it doesn't work.
Maybe I missed something
However, when I use an input type=file, it's works with this example
$("#input").on("change", (e) => {
selectedFile = e.target.files[0];
});
let fileReader = new FileReader();
fileReader.readAsBinaryString(selectedFile);
fileReader.onload = (event)=>{
let data = event.target.result;
let workbook = XLSX.read(data,{type:"binary"});
}
What I would like is for selectedFile to reflect the binary string and not have to go through an input type=file
Thanks for your help
You can create a Blob object from the binary string, then create a File object from the Blob and finally, create a FileReader object from the File object.
var binaryString = "PK\x03\x04\x14\x00\x06\00\x00\x00���N�0\x10E�H�C�-#\b5��\x12*Q>�ēƪc[�ii����\x10B�\x15j7�\x12��{2��h�nm���ƻR\f����U^\x1B7/���%�\x17\x19�rZY�\x14\x1B#1\x19__�f�\x00�q��R4D�AJ�\x1Ah\x15\x16>����V\x11�ƹ\f�Z�9����NV ...";
// create a Blob object
var blob = new Blob([binaryString], { type: "application/vnd.ms-excel" });
// create a File object from the Blob
var file = new File([blob], "file.xlsx");
// create a FileReader object
var reader = new FileReader();
// use the readAsArrayBuffer method to read the file
reader.readAsArrayBuffer(file);
// when the reading is done, log the result
reader.onloadend = function () {
console.log(reader.result);
};

FileReader() API not working for PDF,Excel, Doc format but Working for image format

I used cordova for my application, I want to read all type of file format (ex:image,xls,pdf and etc), for uploading but filereader's working only for image format not for other formats,
Do we have any option to allows formats
e.target.result - will come with null value from filreader
sample code:
let reader = new FileReader();
entry.file(function (file) {
reader.onloadend = function (e) {
var content = e.target.result; // null value when choose .xml,pdf
console.log(content)
};
reader.readAsDataURL(file);
});

Decode Javascript FileReader Base64 in C#

I have the following Javascript-Code for Converting a file into base64:
File.prototype.convertToBase64 = function (callback) {
var FR = new FileReader();
FR.onload = function (e) {
callback(e.target.result)
};
FR.readAsDataURL(this);
}
an example output would be:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj [...] /j+vigYmLtYx9n0tGzJIyZKIzsYyRRWj0RfdWtCiQdF9rH8f18SMciL7X8DJMySJ8uC4JDRWjH8CEiitULVaMf68GQYn2PvskyciSs26tDWr0ooorsWi0WiFIei0Y/10QkQkWWXo+xaNjetdjHo9YlFdi1eiell6LRj/AGIshIUjcKRej1Ws
But I can't decode it with this:
byte[] data = Convert.FromBase64String(base64Image);
It says that it can't recognize the layout of the data. How can I decode the base64 data coming from FileReader in JS in C#?
Thanks to Thomas I found a solution.
The C#-Decoder doesn't like the header: data:image/jpeg;base64,
You can fix it with this short code:
int index = base64Image.IndexOf("base64,") + "base64,".Length;
string base64String = base64Image.Remove(0, index);

How do I get base 64 encoding of a file that use Windows-1251

I have a file uploader input, where I accept a file, convert it to base 64 string, and send the payload to a rest api.
However, when I was encoding base64 for utf-8 files, it was working fine. But if I try to get base64 strings of "window-1251" files, it is not converted to a string properly, and the api throws error instead because the base64 string is not valid content.
So my question is how do I get base64 string of a file that uses window-1251 for encoding?
var reader2 = new FileReader();
reader2.readAsDataURL(file);
reader2.onload = function (e) {
var sContentStream = e.target.result;}
Sorry, but the premise makes no sense.
FileReader.readAsDataURL will always return a valid base64 string from what you gave to it => binary data.
The fact that these bytes represent a text file, with a given encoding is simply ignored by the algorithm.
const rand_data = crypto.getRandomValues(new Uint8Array(50));
const blob = new Blob([rand_data]);
const reader = new FileReader();
reader.onload = e => {
const dataURL = reader.result
const base64 = dataURL.slice(dataURL.indexOf(',')+1);
console.log(base64);
console.log(atob(base64)); // would throw if invalid data
};
reader.readAsDataURL(blob);
So you are looking at the wrong end of the problem: The consumer may have issues with reading windows-1251 encoded text files, but that's not FileReader's fault.
Now, if you are willing to do the conversion from this encoding to UTF-8 in the browser, then that's still doable, but you's need a way to know which encoding the file you've been given is in.
const win_1251 = new Blob([Uint8Array.from([200])]); // И in windows-1251
// to prove it's not UTF-8
readUTF8Text(win_1251); // �
const reencode_reader = new FileReader();
reencode_reader.onload = e => {
const utf_8_arr = new TextDecoder('windows-1251')
.decode(new Uint8Array(reencode_reader.result));
const utf_8 = new Blob([utf_8_arr], {type: 'text/plain'})
makeDataURL(utf_8);
readUTF8Text(utf_8); // И
};
reencode_reader.readAsArrayBuffer(win_1251);
function makeDataURL(blob) {
const reader = new FileReader();
reader.onload = e => {
console.log(reader.result);
};
reader.readAsDataURL(blob);
}
function readUTF8Text(blob) {
const reader = new FileReader();
reader.onload = e => {
console.log(reader.result);
};
reader.readAsText(blob);
}

Convert Angular Material File Input to base64 format

I am using angular 1.7 with material design for my project. i am using angular material file input for this but it gives me result in file format. what i need is to convert that file format into base64 format. i have tried some external libraries but it doesn't work for me. can anyone post code or make a codepen/jsfiddle.
You can try this solution (this is o copy of this post: How to convert file to base64 in JavaScript? ):
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
var file = /*Your file goes here*/
getBase64(file); // prints the base64 string

Categories