如何在 React 中使用 FileReader?

新手上路,请多包涵

我试图让用户“选择文本文件”并将其显示在 UI 中。稍后,我将使用 *.txt 文件中的数据进行绘图。

但是,我无法显示 txt 文件的内容。

有几个模块可用,但我不知道如何使它在 React 中工作。

以下是我找到的示例:

https://stackoverflow.com/a/40146883/10056318

  jsfiddle.net/0GiS0/nDVYd/

谢谢

原文由 scyrt 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 733
1 个回答

我在 MDN 文档中找到了该代码片段,它解决了我的问题,我希望这可以帮助其他人:

 // Callback from a <input type="file" onchange="onChange(event)">
function onChange(event) {
  var file = event.target.files[0];
  var reader = new FileReader();
  reader.onload = function(event) {
    // The file's text will be printed here
    console.log(event.target.result)
  };

  reader.readAsText(file);
}

更多信息,请访问 https://developer.mozilla.org/pt-BR/docs/Web/API/FileReader/onload

原文由 Diego Mello 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进