Search code examples
javascriptfiletypeerror

Converting File input to text in JavaScript


I'm programming a simple JavaScript page to get a file from the user and convert it to a data variable of either binary or text. When I use my code in a click event handler of a button, I get this error:

Uncaught TypeError: file.getAsText is not a function at HTMLButtonElement.sendfButton.onclick

First I browse and select a file, then click on send button.

This is my html input and button:

            <tr>
            <td>
                <button type="button" class="control-button" id="send-file-button">SEND-FILE</button> 
            </td>
            <td>
                    <input type='file' id='myfileinput' multiple><br>
                    <div id='output'>


            </td>
        </tr>

Here are my variables:

                var sendfButton = document.getElementById("send-file-button");
            var fileInput = document.getElementById("myfileinput");

And here is my click event handler:

sendfButton.onclick = function ()
                {
                var files = fileInput.files;
                var accept = {
                binary : ["image/png", "image/jpeg"],
                text   : ["text/plain", "text/css", "application/xml", "text/html" , "text/txt"]
                };
                var file;
                    if (conn && conn.open)
                    {
                        console.log('in1');
                         //convert a file to bytes then send it
                        for (var i = 0; i < files.length; i++)
                        {
                            console.log('in2');
                            file = files[i];
                            // if file type could be detected
                            if (file !== null) 
                            {
                                console.log('in3');
                                if (accept.binary.indexOf(file.type) > -1) 
                                {
                                    console.log('in binary');
                                    // file is a binary, which we accept
                                    var data = file.getAsBinary();
                                    console.log(data + 'dtat');
                                } 
                                else if (accept.text.indexOf(file.type) > -1) 
                                {
                                    console.log('in text');
                                // file is of type text, which we accept
                                var data = file.getAsText();
                                console.log(data + 'dqata');
                                // modify data with string methods
                                }
                            }
                        }

                        console.log('out' + data);
                        conn.send(data);
                        console.log("fSent: " + data);
                        addMessage("<span class=\"selfMsg\">Self: </span> " + data);
                    }
                    else
                    {
                        console.log("failed fsend");
                    } 
                }

It seems to work when I run the code directly, but not when it is activated inside of the button event handler. Code 2 i add filereader but still there is a bug :

sendfButton.onclick = function ()
                {
                var files = fileInput.files;
                var accept = {
                binary : ["image/png", "image/jpeg"],
                text   : ["text/plain", "text/css", "application/xml", "text/html" , "text/txt"]
                };
                var file;
                    if (conn && conn.open)
                    {
                        console.log('in1');
                         //convert a file to bytes then send it
                        for (var i = 0; i < files.length; i++)
                        {
                            console.log('in2');
                            file = files[i];
                            var readers = new FileReader();
                            // if file type could be detected
                            if (file !== null) 
                            {
                                console.log('in3');
                                if (accept.binary.indexOf(file.type) > -1) 
                                {
                                    console.log('in binary');
                                    // file is a binary, which we accept
                                    var data = readers.readAsBinaryString(file);
                                    console.log(data + 'dtat');
                                } 
                                else if (accept.text.indexOf(file.type) > -1) 
                                {
                                    console.log('in text');
                                // file is of type text, which we accept
                                var data = readers.readAsText(file);
                                console.log(data + 'dqata');
                                // modify data with string methods
                                }
                            }
                        }

                        console.log('out' + data);
                        conn.send(data);
                        console.log("fSent: " + data);
                        addMessage("<span class=\"selfMsg\">Self: </span> " + data);
                    }
                    else
                    {
                        console.log("failed fsend");
                    } 
                }

it returns undefined


Solution

  • The File.getAsText() method is obsolete. The File object is a specific kind of a Blob, so you can use the Blob.text() method instead. Replace file.getAsText() in your code with await file.text().

    Edit: Another option that has better browser support is to use FileReader.readAsText(). Your code would look something like this:

    var button = document.getElementById("send-file-button");
    var fileInput = document.getElementById("myfileinput");
    var output = document.getElementById("output");
    
    button.onclick = function () {
      var files = fileInput.files;
      var reader = new FileReader();
      reader.onload = function () {
        output.innerText = reader.result;
      };
      if(files[0]) {
        // This does not return the text. It just starts reading.
        // The onload handler is triggered when it is done and the result is available.
        reader.readAsText(files[0]);
      }
    };
    <input type='file' id='myfileinput' multiple>
    <button type="button" class="control-button" id="send-file-button">SUBMIT-FILE</button> 
    <div id='output'>