javascript - 在 JavaScript 中将文件输入转换为文本

标签 javascript file typeerror

我正在编写一个简单的 JavaScript 页面,以从用户处获取文件并将其转换为二进制或文本的数据变量。当我在按钮的单击事件处理程序中使用我的代码时,出现以下错误:

未捕获类型错误:file.getAsText 不是 HTMLButtonElement.sendfButton.onclick 的函数

首先,我浏览并选择一个文件,然后单击发送按钮。

这是我的 html 输入和按钮:

            <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>

这是我的变量:

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

这是我的点击事件处理程序:

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");
                    } 
                }

当我直接运行代码时它似乎可以工作,但当它在按钮事件处理程序内部激活时则不起作用。 代码2 我添加了文件阅读器,但仍然存在错误:

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");
                    } 
                }

它返回 未定义

最佳答案

File.getAsText() 方法已过时。 File 对象是一种特定类型的 Blob,因此您可以改用 Blob.text() 方法。将代码中的 file.getAsText() 替换为 await file.text()

编辑:具有更好浏览器支持的另一个选项是使用 FileReader.readAsText() 。您的代码将如下所示:

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'>

关于javascript - 在 JavaScript 中将文件输入转换为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60532747/

相关文章:

javascript:原始字符串有方法吗?

javascript - 如何使用 WebStorm 在 TypeScript 而不是 JavaScript 中创建 Cucumber 步骤定义文件?

c - C语言读写文本文件

c - 管道流问题

python - 尝试使用字典中的键时出现 "list indices must be integers"错误

javascript - 输入类型数字,里面有加号、减号或者 "e"显示为空值,为什么?

c++ - 如何在 C++ 中读取和比较 .jpeg 文件中的单个字节?

python - 使用 timedelta 将 15 分钟添加到当前时间戳

javascript - React - TypeError : this. props.AccountId 不是函数

javascript - 为什么 shuffle 在 React 中不起作用?