How to convert a Base64 String to a javascript file, for example, how from a file input form?

I want to convert a Base64String extracted from a file (for example: "AAAAA .... ~") to a javascript file object.

The javascript file object, which I mean, looks like this code:

HTML:

<input type="file" id="selectFile" > 

JS:

 $('#selectFile').on('change', function(e) { var file = e.target.files[0]; console.log(file) } 

'file' is a javascript file object. So I want to convert a base64 string to a javascript file object like this.

I just want to get the object file by decrypting the base64 string (encoded by another application from the file) without the html file input form.

Thanks.

+5
source share
4 answers

Method 1: only works for dataURL, not for other types of URLs.

 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); 

Method 2: works for any type of url (http-url, dataURL, blobURL, etc.)

 //return a promise that resolves with a File instance function urltoFile(url, filename, mimeType){ return (fetch(url) .then(function(res){return res.arrayBuffer();}) .then(function(buf){return new File([buf], filename, {type:mimeType});}) ); } //Usage example: urltoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt', 'text/plain') .then(function(file){ console.log(file); }) 
+16
source
 const url = 'data:image/png;base6....'; fetch(url) .then(res => res.blob()) .then(blob => { const file = new File([blob], "File name") }) 

Base64 String -> Blob -> File.

+2
source

Lights up

JAVASCRIPT

 <script> function readMtlAtClient(){ mtlFileContent = ''; var mtlFile = document.getElementById('mtlFileInput').files[0]; var readerMTL = new FileReader(); // Closure to capture the file information. readerMTL.onload = (function(reader) { return function() { mtlFileContent = reader.result; mtlFileContent = mtlFileContent.replace('data:;base64,', ''); mtlFileContent = window.atob(mtlFileContent); }; })(readerMTL); readerMTL.readAsDataURL(mtlFile); } </script> 

HTML

  <input class="FullWidth" type="file" name="mtlFileInput" value="" id="mtlFileInput" onchange="readMtlAtClient()" accept=".mtl"/> 

Then mtlFileContent has your text as a decrypted string!

-1
source

You need to use FileReader. Here is the fiddle.

 $('#selectFile').on('change', function(e) { var file = e.target.files[0]; var fileReader = new FileReader(); fileReader.onload = function (e) { var base64 = e.target.result; console.log(base64); }; fileReader.readAsDataURL(file); }); 
-2
source

Source: https://habr.com/ru/post/925136/


All Articles