2

How to get data like this:

data:application/pdf;base64,JVBERi0xLjQKJeHp69MKMSAwIG9iago8PC9UeXBlIC9DYXR…AKdHJhaWxlcgo8PC9TaXplIDE4Ci9Sb290IDEgMCBSPj4Kc3RhcnR4cmVmCjg4MzEzCiUlRU9G 

from input file

$('#file').change(function(e) {
  var file = $('#file')[0].files;
  for (var i = 0; i < file.length; i++) {
    console.log(file[i].name)
    console.log(file[i].type)
    console.log(file[i].size)
  }



});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="file" id="file" name="file" multiple="">

I got the sample like

function readURL(input) {
    var reader = new FileReader();
    reader.onload = function(e) {
        console.log(e.target.result)
    };
    reader.readAsDataURL(input);
}

I need to get it from on change of input file because i want to put it in the href of an anchor like

<a class="image" href=' + e.target.result + '><img style="width:150px; height:150px;" u="image" src=' + e.target.result + '></a>

so that my code looks like

$('#file').change(function(e) {
    var file = $('#file')[0].files;
    for (var i = 0; i < file.length; i++) {
        $('body').append('<a class="image" href=' + e.target.result + '><img style="width:150px; height:150px;" u="image" src=' + e.target.result + '></a>')
    }
});
4
  • You need to append it in reader.onload handler and calling readURL() from for loop. See e.g: jsfiddle.net/L5w7fb7j Commented Nov 7, 2015 at 10:25
  • do i need to put return?like return e.target.result? @A.Wolff Commented Nov 7, 2015 at 10:26
  • 1
    See jsFiddle, but you cannot return from an ansyc method, the onload event. You could use a deferred object but that's quite useless here Commented Nov 7, 2015 at 10:27
  • @A.Wolff can you write it as answer i will accept it.. I didnt know it should be like that. Also i didnt know that filereader is async. to reduce un answered question Commented Nov 7, 2015 at 10:37

1 Answer 1

2

What you want is adding anchor once you get the data file(s) available. The easiest way it to append these elements from reader onload event. See e.g:

function readURL(input) {
    var reader = new FileReader();
    reader.onload = function(e) {
         // here data is available, you can append it
         $('body').append('<a class="image" href=' + e.target.result + '><img style="width:150px; height:150px;" u="image" src=' + e.target.result + '></a>')
    };
    reader.readAsDataURL(input);
}

$('#file').change(function(e) {

    var files = $('#file')[0].files;

    for (var i = 0; i < files.length; i++) {
         readURL(files[i]);       
    }
});
Sign up to request clarification or add additional context in comments.

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.