从前端获取上传文件内容 (html + js)

33 阅读1分钟

用于前端解析上传文件,不上传到服务器

代码

此处为 html + js 实现,如果使用包装的UI组件,可以将 file 灵活替换

<input type="file" accept=".csv" id="csvFile" />
<script>
  const csvFile = document.getElementById("csvFile");
  csvFile.addEventListener("change", CsvUploader);
  function CsvUploader(event) {
    const file = event.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => {
      // type: string
      const text = e.target.result;
      console.log(text);
    };
    reader.readAsText(file);
  };
</script>

效果

image.png