Search code examples
javascriptdrag-and-dropfilereader

Load Textfile via Drag and Drop on Textarea


I'm trying to add the ability to drag and drop a textfile into a textarea. However, I'm getting the following error.

Uncaught TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.

enter image description here

Which according to the error line 19 is

reader.readAsText(input.files[0],"UTF-8");

I see it's saying parameter 1 is not of type 'Blob'; However, can someone please explain why is this error showing and what can I do to fix this error?

function dropfile(input) {
  var reader = new FileReader();  
  reader.onload = function(e) {            
    notepad.value = e.target.result;
  }        
  reader.readAsText(input.files[0],"UTF-8");
};
notepad.ondrop = function(e) {
  this.value = "";
  e.preventDefault();
  var file = e.dataTransfer.files[0];
  dropfile(file);
};
html, body {
  height: 100%;
  padding: 0;
  margin: 0;
}

#notepad {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  border: 0;
  padding: 1em;
  width: calc(100vw - 2em);
  resize: none;
}
#notepad:focus {
  outline: 0;
}
<textarea id="notepad" placeholder="drag and drop your .txt file"></textarea>


Solution

  • You are passing the file to dropfile function.

    var file = e.dataTransfer.files[0];
    dropfile(file);
    

    in dropfile function you are consuming it wrong.

    reader.readAsText(input.files[0],"UTF-8"); 
    

    you should change the line to

    reader.readAsText(input,"UTF-8"); 
    

    Try the below snippet.

    function dropfile(file) {
      var reader = new FileReader();
      reader.onload = function(e) {
        notepad.value = e.target.result;
      };
      reader.readAsText(file, "UTF-8");
    }
    
    notepad.ondrop = function(e) {
      e.preventDefault();
      var file = e.dataTransfer.files[0];
      dropfile(file);
    };
    html,
    body {
      height: 100%;
      padding: 0;
      margin: 0;
    }
    
    #notepad {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      border: 0;
      padding: 1em;
      width: calc(100vw - 2em);
      resize: none;
    }
    
    #notepad:focus {
      outline: 0;
    }
    <textarea
      id="notepad"
      placeholder="drag and drop your .txt file"
    ></textarea>