1


Hello! I'am trying to make it work a function called loadDocument, who need a url of the loaded files from the user local computer to work. I'm writing an API to load document from local user computer, and show it on a web reader.

This is my upload button : <input type="file" id="input" onchange="module.onLoadSelection();" alt="Browse" name="upload"/>

This is my function without fileReader :

var onLoadSelection = function () {
    var select = document.getElementById('input');
    if (select && select.value) {
        var id= '';
        var url = select.files.item(0).name;
        module.loadDocument(url,id);
    }
};

This is my function with fileReader :

var loadTest = function (input) {
    var file = document.querySelector('input[type=file]').files[0];
    console.log("file loaded! ->", file); // i can read the obj of my file
    var reader = new FileReader();

    var id = ''; // don't need rightnow
    var url = reader.readAsDataURL(file);
    console.log("url :", url); // show me undefined....
    module.loadDocument(url,id);
}

What i am trying is to get the url of the loaded file from user computer to get my function loadDocument working. She need a url parameter to work.

loadDocument is an API function, i assume i can't get the filepath of my user due to security reason.

What do i need to change/update on my loadDocument(); function to work?

Edit : In fact, nothing to change. The correct way to read my file was : <input type="file" id="input" onchange="module.onLoadSelection(this.files);" alt="Browse" name="upload"/>

var onLoadSelection = function (files) {
    if (files && files.length == 1) {
       var id = '';
       var url = URL.createObjectURL(files[0]);
       module.loadDocument(url,id);
    }
};
Kubadev
  • 867
  • 10
  • 25

3 Answers3

4

Don't use a FileReader at all.

When you want to display a File (or a Blob) that is in the browser's memory or on user's disk, then all you need is to generate an URL that do point to this memory slot.
That's exactly what URL.createObjectURL(blob) does: it returns a Blob URI (blob://) that points to the data either in memory or on the disk, acting exactly as a simple pointer.

This method has various advantages over the FileReader.readAsDataURL() method. To name a few:

  • Store the data in memory only once, when FileReader would need it at reading, then generate a copy as an base64 encoded, and an other one at displaying...
  • Synchronous. Since all it does is to generate a pointer, no need to make it async.
  • Cleaner code.

const module = {
  loadDocument: (url) => {
    document.body.append(
      Object.assign(
        document.createElement('iframe'),
        { src: url }
      )
    )
  }
};

document.querySelector('input[type=file]').addEventListener('input', function (evt) {
    var file = this.files[0];
    var url = URL.createObjectURL(file);
    module.loadDocument(url);
});
<input type="file">
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • Thank you so much @Kaiido, this is completly working ! I really appreciate your answer, it's helped me to understand more deeply the file managment in Javascript. I started conding in JS 1 month ago... Best regards from France, thank you again. – Kubadev May 28 '19 at 12:05
1
 function PreviewFiles(input) {
        if (input.files && input.files[0]) {
             var reader = new FileReader();
             reader.onload = function (e) {
             //alert(e.target.result);
                 $('#pclogo').prop('src', e.target.result)
                    .width(200)
                    .height(200);
                    var base64result = e.target.result.split(',')[1];
                $('input[name="logo"]').val(base64result);
            };
            reader.readAsDataURL(input.files[0]);

            }

        }
0

File objects have a readAsDataURL method.

Use that.

  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.addEventListener("load", function () {
    doSomethingWithAUrl(reader.result);
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thank you @Quentin to lead me to the correct way of writing this function. In my case, do i need to fire my function loadDocument(url,id) in the eventlistener or use the reader instance "reader.readAsDataURL(file)" as url parameter of my function ? – Kubadev May 28 '19 at 09:49
  • @KubNetwork — Since `reader.readAsDataURL(file)` doesn't return a URL, and since I wrote `doSomethingWithAUrl` as an example function name … – Quentin May 28 '19 at 09:56
  • No. FileReader does, File objects don't. – Kaiido May 28 '19 at 10:08