HTML 文本区域中未加载文件

files not loading in HTML text area

我正在尝试从文件已存在的 file/JOHN 目录加载 3 个文件。

文件格式如下。假设它们位于以下位置(在 file/JOHN 文件夹内):C:/john/file/JOHN/

file1_1555077233.csv
file2_1555077233.csv 
file3_1555077233.csv

因为我是在我的 Windows 机器上测试它,所以我把它放在这个位置 C:/john/file/JOHN/。然而,最终,在 RHEL 服务器上,它会像这样 /srv/users/JOHN/ 所以我在 Windows 机器上使用用户目录来进行测试。

文本区域中没有显示文件。但是,当我点击 button.What 时,文本区域会在 1 秒后显示,我做错了吗?

单击 Download File 按钮后,下面的代码会在 1 秒后显示一个文本区域。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8"/>
    <title>LoadFiles</title>
    <link rel="stylesheet" href="built/style.css"/>
    <script type="text/javascript">
        var interval;
        function loadFiles() {
            interval = setInterval(displayTextArea, 1000);


        }
        function displayTextArea() {
              console.log(new Date() + " ");

              document.getElementById("downloadtextArea").innerHTML =
                 '<textarea maxlength="500" cols="30" rows="5"></textarea>'; 


                const requests = [
                  'file1_1555077233.csv',
                  'file2_1555077233.csv ',
                  'file3_1555077233.csv'
                ].map(file => {

                 return fetch('file:///C:/john/file/JOHN/' + file)
                    .then(response => response.text())
                    .catch(console.error)
                })

                Promise.all(requests)
                  .then(contents => contents.join('\n'))
                  .then(content => {

                    //container.innerHTML = `<textarea>${content}</textarea>`
                    content.innerHTML = `<textarea>${content}</textarea>`
                  })


                clearInterval(interval);




            }






    </script>
</head>
<body>


<button id="downloadFileButton" onclick="loadFiles()">Download File</button>
<div id ="downloadtextArea"></div>


</body>
</html>

我执行的故障排除步骤:

在浏览器中复制以下路径:

file:///C:/john/file/JOHN/file1_1555077233.csv 我看到了文件

您正试图在您的响应数据上设置 innerHTML,而不是在 DOM 元素上。

在您的 displayTextArea() 函数中:

function displayTextArea() {
  console.log(new Date() + " ");
  const requests = [
    'file1_1555077233.csv',
    'file2_1555077233.csv ',
    'file3_1555077233.csv'
  ].map(file => {
    return fetch('file:///C:/john/file/JOHN/' + file)
    .then(response => response.text())
    .catch(console.error)
  })

  Promise.all(requests)
  .then(contents => contents.join('\n'))
  .then(content => {
    document.getElementById('downloadtextArea').innerHTML = `<textarea>${content}</textarea>`
  })
}

文本区域在 1 秒后显示的原因是您在 loadfiles() 方法中设置了 1 秒的间隔。

您能具体说明单击“下载”按钮后控制台中显示的是什么错误吗? 是低于错误吗? 获取 API 无法加载 file:///C:/john/file/JOHN/file1_1555077233.csv。对于 CORS 请求,URL 方案必须是 "http" 或 "https"。