使用 fetch() 上传本地 CSV 文件失败,无法执行 FileReader()

Fail to upload local CSV file with fetch() and fail to execute FileReader()

我正在尝试使用 JavaScript 操作 本地 CSV 文件。我的目的是在我的网站上显示来自我的 CSV 的数据,例如我们使用 JSON 格式的外部 API。

const csvLocalFile =
  "http://XXX/.../file.csv";

const openFile = async () => {
  const csv = await fetch(csvLocalFile).then();
  let reader = new FileReader();
  reader.onload = function () {
    let text = reader.result;
    filecontent = text.replace("", "");
  };
  reader.readAsText(csv.files[0]);
};

openFile();

Chrome 显示此错误:

TypeError: 无法读取未定义的属性(读取“0”)

当我从“reader.readAsText(csv.files[0])”中删除“[0]”时,出现此消息错误:

TypeError:无法在 'FileReader' 上执行 'readAsText':参数 1 不是 'Blob'.

类型
  1. .then() 不是问题,事实证明没有 fn 也能正常工作。但无论如何你都应该删除它。
  2. FileReader 无法读取响应对象,只能读取文件和 Blob...
  3. 你说你试图读取一个本地文件,但是你使用 fetch 来获取远程文件,那么你真正想要做什么?不清楚如何帮助您...
  4. csv 是无效的 json 数据,因此您不能使用 .then((res) => res.JSON())
  5. 旁边res.JSON()写错了,应该都是小写的...res.json()
  6. FileReader 被认为是遗留的,因此您不再需要它...请改用 await blob.text()

这里有两个如何使用 fetch 读取 1 个远程文件的例子

// Simulate getting a file from eg a file input or drag and drop
const file = new File(['id,name\n10,bob'], 'file.csv', { type: 'text/csv' })
// Simulate a remote location to get the csv from
const url = URL.createObjectURL(file)

const csvLocalFile = url // http://XXX/.../file.csv

const openFile = async () => {
  const response = await fetch(csvLocalFile)
  const text = await response.text()
  console.log(text)
}

openFile()

...和另一个从用户输入中选择的实际本地文件

const fileInput = document.querySelector('#fileInput')

fileInput.onchange = async () => {
  const file = fileInput.files[0]
  const text = await file.text()
  console.log(text)
}

// ignore code below this line...

// Create a dummy file that we can use to change the file input with...
const dummyFile = new File(['id,name\n10,bob'], 'file.csv', { type: 'text/csv' })
// Used for creating a new FileList in a round-about way
const b = new ClipboardEvent('').clipboardData || new DataTransfer()
b.items.add(dummyFile)
// simulate picking a file
fileInput.files = b.files
fileInput.onchange()
<input type="file" id="fileInput">