首页 > 解决方案 > 读取 Promise 结果变量

问题描述

我正在读取文件数据作为数据字符串以及文件名

我的代码将生成正确的文件名,但文件数据显示为空 {}

预期的输出是

[{
    filename: "name1.txt",
    filedata: "data:text/plain;base64,VGhpc.."
}, {
    filename: "name2.txt",
    filedata: "data:text/plain;base64,VGhpc.."
}]

我的代码是

function readFile(file) {
  return new Promise(function(resolve, reject) {
    let fr = new FileReader();
    fr.onload = function() {
      resolve(fr.result);
    };
    fr.onerror = function() {
      reject(fr);
    };
    fr.readAsDataURL(file)
  });
}

// Handle multiple fileuploads
function uploadForm() {
  let files = $('#file')[0].files // ev.currentTarget.files;
  let readers = [];
  if (!files.length) return;
  for (let i = 0; i < files.length; i++) {
    readers.push({
      "filedata": readFile(files[i]),
      "filename": files[i].name
    });
  }
  Promise.all(readers).then((values) => {
    console.log(JSON.stringify(values));
    return
  });
}

function showMessage(e) {
  $('#progress').html(e);
  $('#file').val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<body>
  <table cellpadding="5px">
    <tr>
      <td>Select File:</td>
      <td>
        <input id="file" type="file" value="" accept=".csv,.xlsx,.docx,.rtf,.pdf,.pptx,.txt" multiple>
      </td>
    </tr>
    <tr>
      <td colspan="2"><button onclick="uploadForm();" id="upload">Upload</button>&emsp;</td>
    </tr>
    <tr>
      <td colspan="2">
        <div id="progress"></div>
      </td>
    </tr>
  </table>
</body>

</html>

标签: javascriptpromise

解决方案


我只需将 Promise 推入一个数组即可修复此问题,因此您可以轻松地使用Promise.all. { filedata, filename }然后,当您获得结果数组时,将其映射到对象数组。

这是不同的部分:

  for (let i = 0; i < files.length; i++) {
    readers.push(readFile(files[i]));
  }
  Promise.all(readers).then((values) => {
    const result = values.map((filedata,i) => ({
      filedata,
      filename: files[i].name
     }));
    
    console.log(JSON.stringify(result));
    return
  });

你的整个例子,修复。

function readFile(file) {
  return new Promise(function(resolve, reject) {
    let fr = new FileReader();
    fr.onload = function() {
      resolve(fr.result);
    };
    fr.onerror = function() {
      reject(fr);
    };
    fr.readAsDataURL(file)
  });
}

// Handle multiple fileuploads
function uploadForm() {
  let files = $('#file')[0].files // ev.currentTarget.files;
  let readers = [];
  if (!files.length) return;
  for (let i = 0; i < files.length; i++) {
    readers.push(readFile(files[i]));
  }
  Promise.all(readers).then((values) => {
    const result = values.map((filedata,i) => ({
      filedata,
      filename: files[i].name
     }));
    
    console.log(JSON.stringify(result));
    return
  });
}

function showMessage(e) {
  $('#progress').html(e);
  $('#file').val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<body>
  <table cellpadding="5px">
    <tr>
      <td>Select File:</td>
      <td>
        <input id="file" type="file" value="" accept=".csv,.xlsx,.docx,.rtf,.pdf,.pptx,.txt" multiple>
      </td>
    </tr>
    <tr>
      <td colspan="2"><button onclick="uploadForm();" id="upload">Upload</button>&emsp;</td>
    </tr>
    <tr>
      <td colspan="2">
        <div id="progress"></div>
      </td>
    </tr>
  </table>
</body>

</html>


推荐阅读