1

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

2
  • @GolezTrol doesn't seem to be PHP involved? Commented Feb 1, 2017 at 12:16
  • Not PHP, only javascript Commented Feb 1, 2017 at 12:20

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

It's only run in chrome, not in IE
@cardonchas i see, IE is always a pain in the azz. I edited my post, can you try javascript version?
It's run in chrome, but not in IE
works for image but failed for a pdf file I used application/pdf as mime type of the base64 encoded data
0

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"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.