How to Convert Base64 String to JavaScript File Object Like as from File Input Form

How to convert Base64 String to javascript file object like as from file input form?

Way 1: only works for dataURL, not for other types of url.

 function dataURLtoFile(dataurl, filename) {         var arr = dataurl.split(','),            mime = arr[0].match(/:(.*?);/)[1],            bstr = atob(arr[1]),             n = bstr.length,             u8arr = new Uint8Array(n);                    while(n--){            u8arr[n] = bstr.charCodeAt(n);        }                return new File([u8arr], filename, {type:mime});    }        //Usage example:    var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');    console.log(file);

Convert base64 png data to javascript file objects

You can create a Blob from your base64 data, and then read it asDataURL:

var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];

var the_file = new Blob([window.atob(png)], {type: 'image/png', encoding: 'utf-8'});

var fr = new FileReader();
fr.onload = function ( oFREvent ) {
var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
v = atob(v);
var good_b64 = btoa(decodeURIComponent(escape(v)));
document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);

Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/


Alternatively, you can use .readAsText, it works fine, and its more elegant.. but for some reason text does not sound right ;)

fr.onload = function ( oFREvent ) {
document.getElementById("uploadPreview").src = "data:image/png;base64,"
+ btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here

Full example: http://jsfiddle.net/tTYb8/3/

Convert string base64 to Object JS file

In order to decode base64 to string you'll need to use atob.

<html>

<body>
<script id="output" type="module"></script>
<script type="module">
const content = atob("ZXhwb3J0IGRlZmF1bHQgewpsYWJlbDogIlRlc3QgZmlsZSBKUyIsCiAgdmlld0JveDogIjAgMCA4MDAgMTEyMCIsCiAgbG9jYXRpb25zOiBbCiAgICB7CiAgICAgIGlkOiAiMDEiLAogICAgICBwYXRoOgogICAgICAgICJNIDQ0NS43MyA3NDcuNjcgMjA1LjYgNTMzLjQ0IDU3NC4yMiAxIDc5Ny43MyAxOTUuNjMgNzk5IDIwNC43NCA1MzUuNDkgNDkyLjc0IDU5MS44MiA1ODcuMjIgNDQ1LjczIDc0Ny42NyBaIgogICAgfSwKICAgIHsKICAgICAgaWQ6ICIwMiIsCiAgICAgIHBhdGg6ICJNIDEgODE4LjM4IDIwMy4wOCA1MzAuOSA0NDMuMzkgNzQ5Ljc1IDEwNS4yOSAxMTE5LjM4IDEgODE4LjM4IFoiCiAgICB9CiAgXQp9Ow==");

console.log(content);
const body = document.body;
const script = document.getElementById("output");
script.text = content;
script.src = "content.js";

//import * as example from "./content.js";
//console.log(example.locations);
</script>
</body>

</html>

Is there possible to convert a base64 code to a file like it has been got from input type file?

Instead of your filefy function to create a virtual File object, you could simply use a Blob:

var blob = new Blob([image], { type: "image/jpeg"});
fd.append('file[]', blob, new Date().getTime()+'.jpg');

You might need to convert the base64 string representation of the image to a byte array (or use canvas.toBlob).

More infos:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
https://developer.mozilla.org/en-US/docs/Web/API/Blob

Get Base64 encode file-data from Input Form

It's entirely possible in browser-side javascript.

The easy way:

The readAsDataURL() method might already encode it as base64 for you. You'll probably need to strip out the beginning stuff (up to the first ,), but that's no biggie. This would take all the fun out though.

The hard way:

If you want to try it the hard way (or it doesn't work), look at readAsArrayBuffer(). This will give you a Uint8Array and you can use the method specified. This is probably only useful if you want to mess with the data itself, such as manipulating image data or doing other voodoo magic before you upload.

There are two methods:

  • Convert to string and use the built-in btoa or similar
    • I haven't tested all cases, but works for me- just get the char-codes
  • Convert directly from a Uint8Array to base64

I recently implemented tar in the browser. As part of that process, I made my own direct Uint8Array->base64 implementation. I don't think you'll need that, but it's here if you want to take a look; it's pretty neat.

What I do now:

The code for converting to string from a Uint8Array is pretty simple (where buf is a Uint8Array):

function uint8ToString(buf) {
var i, length, out = '';
for (i = 0, length = buf.length; i < length; i += 1) {
out += String.fromCharCode(buf[i]);
}
return out;
}

From there, just do:

var base64 = btoa(uint8ToString(yourUint8Array));

Base64 will now be a base64-encoded string, and it should upload just peachy. Try this if you want to double check before pushing:

window.open("data:application/octet-stream;base64," + base64);

This will download it as a file.

Other info:

To get the data as a Uint8Array, look at the MDN docs:

  • https://developer.mozilla.org/en/DOM/FileReader


Related Topics



Leave a reply



Submit