Reputation: 13
how must I decode base64 string and download file from base64 string? Previosly, I encoded a file with:
var strEncoded="";
file = $('#fileinput1')[0].files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
strEncoded = reader.result;
};
Thank you
Upvotes: 1
Views: 4306
Reputation: 136638
Don't use the b64 version, but instead go directly with the File object you've got from your input.
Up to date browsers do support anchor's download
attribute, then you just have to do a.href = URL.createObjectURL(yourFile); a.download = 'yourfile.whateverExtension'
.
For older browsers, there are a few hacks, all condensed in the great FileSaver.js library.
Then all you need to do is
var inp = document.querySelector('input');
inp.onchange = function(){
saveAs(this.files[0], 'yourFile.extension');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.js"></script>
<input type="file"/>
Upvotes: 0
Reputation: 1921
You can create a <a>
link and give the data to its href
. For example i used a data/image base64 like this:
<a href="data:image/png;base64,iVBORw0K........" download>Download</a>
download
attribute would do the work.
Or simply try this:
location.href = strEncoded;
And in a function:
download(dataUrl) {
location.href = dataUrl;
}
<a href="javascript:;" onclick="download(strEncoded);">Download</a>
Upvotes: 1