Convert binary data to base64 with javascript
Try the btoa
function:
var data = btoa(r);
Convert binary data to base64 does not work with btoa unescape
You've said you're using axios.get
to get the image from the server. What you'll presumably get back will be a Buffer
or ArrayBuffer
or Blob
, etc., but it depends on what you do with the response you get from axios
.
I don't use axios
(never felt the need to), but you can readily get a data
URI for binary data from the server via fetch
:
// 1.
const response = await fetch("/path/to/resource");
// 2.
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
// 3.
const buffer = await response.arrayBuffer();
// 4.
const byteArray = new Uint8Array(buffer);
// 5.
const charArray = Array.from(byteArray, byte => String.fromCharCode(byte));
// 6.
const binaryString = charArray.join("");
// 7.
const theImage = btoa(binaryString);
Or more concisely:
const response = await fetch("/path/to/resource");
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
const buffer = await response.arrayBuffer();
const binaryString = Array.from(new Uint8Array(buffer), byte => String.fromCharCode(byte)).join("");
const theImage = btoa(binaryString);
Here's how that works:
- We request the image data.
- We check that the request worked (
fetch
only rejects its promise on network errors, not HTTP errors; those are reported via thestatus
andok
props. - We read the body of the response into an
ArrayBuffer
; the buffer will have the binary image data. - We want to convert that buffer data into a binary string. To do that, we need to access the bytes individually, so we create a
Uint8Array
(using that buffer) to access them. - To convert that byte array into a binary string, we need to convert each byte into its equivalent character, and join those together into a string. Let's do that by using
Array.from
and in its mapping function (called for each byte), we'll useString.fromCharCode
to convert the byte to a character. (It's not really much of a conversion. The byte 25 [for instance] becomes the character with character code 25 in the string.) - Now we create the binary string by joining the characters in that array together into one string.
- Finally, we convert that string to Base64.
Looking at the docs, it looks like axios
lets you provide the option responseType: "arraybuffer"
to get an array buffer. If I'm reading right, you could use axios
like this:
const response = await axios.get("/path/to/resource", {responseType: "arraybuffer"});
const binaryString = Array.from(new Uint8Array(response.body), v => String.fromCharCode(v)).join("");
const theImage = btoa(binaryString);
convert binary data to base-64 javaScript
My problem is solved . I use dropzone plugin to get the response from server and because of this I get binary data as a text reponse and it make my problems. I just go to dropzone.js and change 2 minor things to get the response in type of arraybuffer :
xhr.responseType = 'arraybuffer'; ( line 1246)
This is new line to get the response in type of arrayBuffer, and then create a Blob object from the arraybuffer response .
response = xhr.response; (line 1305 )
Change it to get response inseted TextRrsponse..
I hope that it will help somebody...
Thanks everyone !
How can you encode a string to Base64 in JavaScript?
You can use btoa()
and atob()
to convert to and from base64 encoding.
There appears to be some confusion in the comments regarding what these functions accept/return, so…
btoa()
accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.atob()
returns a “string” where each character represents an 8-bit byte – that is, its value will be between0
and0xff
. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.
See also:
- How do I load binary image data using Javascript and XMLHttpRequest?
Most comments here are outdated. You can probably use both btoa()
and atob()
, unless you support really outdated browsers.
Check here:
- https://caniuse.com/?search=atob
- https://caniuse.com/?search=btoa
Convert Binary.toString('encode64') back to Binary
This question has some helpful info: How to do Base64 encoding in node.js?
The Buffer class itself does the conversion:
var base64data = Buffer.from('some binary data', 'binary').toString('base64');
console.log(base64data);
// -> 'c29tZSBiaW5hcnkgZGF0YQ=='
var originaldata = Buffer.from(base64data, 'base64');
console.log(originaldata);
// -> <Buffer 73 6f 6d 65 20 62 69 6e 61 72 79 20 64 61 74 61>
console.log(originaldata.toString());
// -> some binary data
Creating a BLOB from a Base64 string in JavaScript
The atob
function will decode a Base64-encoded string into a new string with a character for each byte of the binary data.
const byteCharacters = atob(b64Data);
Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the .charCodeAt
method for each character in the string.
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
You can convert this array of byte values into a real typed byte array by passing it to the Uint8Array
constructor.
const byteArray = new Uint8Array(byteNumbers);
This in turn can be converted to a BLOB by wrapping it in an array and passing it to the Blob
constructor.
const blob = new Blob([byteArray], {type: contentType});
The code above works. However the performance can be improved a little by processing the byteCharacters
in smaller slices, rather than all at once. In my rough testing 512 bytes seems to be a good slice size. This gives us the following function.
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
const blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);
window.location = blobUrl;
Full Example:
const b64toBlob = (b64Data, contentType='', sliceSize=512) => { const byteCharacters = atob(b64Data); const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); }
const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); }
const blob = new Blob(byteArrays, {type: contentType}); return blob;}
const contentType = 'image/png';const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
const blob = b64toBlob(b64Data, contentType);const blobUrl = URL.createObjectURL(blob);
const img = document.createElement('img');img.src = blobUrl;document.body.appendChild(img);
Binary file to base64 nodejs
I guess you were following the section Make a request and save the response
of the offical document Quickstart: Convert text-to-speech using Node.js
to write your code, as below.
var request = require('request');
let options = {
method: 'POST',
baseUrl: 'https://westus.tts.speech.microsoft.com/',
url: 'cognitiveservices/v1',
headers: {
'Authorization': 'Bearer ' + accessToken,
'cache-control': 'no-cache',
'User-Agent': 'YOUR_RESOURCE_NAME',
'X-Microsoft-OutputFormat': 'riff-24khz-16bit-mono-pcm',
'Content-Type': 'application/ssml+xml'
},
body: body
};
function convertText(error, response, body){
if (!error && response.statusCode == 200) {
console.log("Converting text-to-speech. Please hold...\n")
}
else {
throw new Error(error);
}
console.log("Your file is ready.\n")
}
// Pipe the response to file.
request(options, convertText).pipe(fs.createWriteStream('sample.wav'));
So I change the offical code above to create a function encodeWithBase64
to encode body
with Base64.
function encodeWithBase64(error, response, body){
if (!error && response.statusCode == 200) {
var strBase64 = Buffer.from(body).toString('base64');
console.log(strBase64);
}
else {
throw new Error(error);
}
console.log("Your file is encoded with Base64.\n")
}
// Pipe the response to file.
request(options, convertText);
Or you can use the npm packages base64-stream
and get-stream
to get the string with Base64 from body
.
var base64 = require('base64-stream');
const getStream = require('get-stream');
(async () => {
var encoder = new base64.Base64Encode();
var b64s = request(options).pipe(encoder);
var strBase64 = await getStream(b64s);
console.log(strBase64);
})();
Otherwise, stream-string
also can do it.
var base64 = require('base64-stream');
const ss = require('stream-string');
var encoder = new base64.Base64Encode();
var b64s = request(options).pipe(encoder);
ss(b64s).then(data => {
console.log(data);
})
Related Topics
Replace HTML Page With Contents Retrieved Via Ajax
How to Replace Text Inside a Div Element
Text-Overflow Ellipsis on Left Side
How to Silently Hide "Image Not Found" Icon When Src Source Image Is Not Found
Programmatically Selecting Text in an Input Field on iOS Devices (Mobile Safari)
Can Jquery Get All CSS Styles Associated With an Element
Get Element CSS Property (Width/Height) Value as It Was Set (In Percent/Em/Px/Etc)
What Is the Cleanest Way to Disable CSS Transition Effects Temporarily
Use ≪Canvas≫ as a CSS Background
Getcurrentposition() and Watchposition() Are Deprecated on Insecure Origins
Uncaught Error: Security_Err: Dom Exception 18 When I Try to Set a Cookie
Coordinates of Selected Text in Browser Page
Uploading 'Canvas' Image Data to the Server
Jquery Event Won't Fire After Ajax Call
Why Write ≪Script Type="Text/JavaScript"≫ When the Mime Type Is Set by the Server