-2

update: Finally I find out the reason myself, the reason is: actually I used Angular's ng-href at the same time, which prefix a unsafe to the data url, I have to config the compiler service to waive that restriction like:

.config( [
    '$compileProvider',
    function( $compileProvider )
    {   
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension):/);
        // Angular before v1.2 uses $compileProvider.urlSanitizationWhitelist(...)
    }
])

Which talks about here: Angular changes urls to "unsafe:" in extension page


All:

What I want to do is read in a image as dataURL and give it to a tag as download:

<input type='file' name='doc' />
<a href="#" download="data">Download</a>
<script>
            var fileOBJ = $("input")[0]
                        .files[0];
            var reader = new FileReader();
            reader.onload = function(e){
                $("a")[0].href=e.target.result;
            }
            reader.onerror = function(err){
                console.log(err);
            }
            reader.readAsDataURL(fileOBJ);
</script>

The download always failed.

But if I use a <img> instead of <a>, then the image can shown up. I do not know what is wrong with the <a> link

Community
  • 1
  • 1
Kuan
  • 11,149
  • 23
  • 93
  • 201

2 Answers2

1

Specify the atrribute download on the link. Like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='file' name='doc' />
<a download="filename" href="#">Download</a>
<script>
  $("input").change(function() {
    var fileOBJ = $("input")[0]
      .files[0];
    var reader = new FileReader();
    reader.onload = function(e) {
      $("a")[0].href = e.target.result;
      // if you want to change the download filename
      // $($("a")[0]).attr("download", "some other filename");
    }
    reader.onerror = function(err) {
      console.log(err);
    }
    reader.readAsDataURL(fileOBJ);
  })
</script>
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
1

You try to call readAsDataURL when there is any file selected, what throws an error. Use this method after you select some file.

var reader = new FileReader();
reader.onload = function(e){
   $("a")[0].href = e.target.result;
};

reader.onerror = function(err){
   console.log(err);
};

$('#inpFile').on('change',function(){
   reader.readAsDataURL(this.files[0]);
});
Paweł
  • 4,238
  • 4
  • 21
  • 40