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

Time:04-09

I'm trying to manipulate a local CSV file with JavaScript. My purpose is to display datas from my CSV on my website, like we were using an external API in JSON format for example.

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 display this error :

TypeError: Cannot read properties of undefined (reading '0')

When I delete "[0]" from "reader.readAsText(csv.files[0])", I have this message error :

TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.

CodePudding user response:

  1. A empty .then() isn't the problem, turns out it works fine without a fn. but you should remove it regardless.
  2. The FileReader can't read Response objects, only File & Blobs...
  3. You say that you try to read a local file, but yet you use fetch to get a remote file, so what is it that your really trying to do? it's unclear of how to help you...
  4. a csv isn't valid json data, so you can't use .then((res) => res.JSON())
  5. beside res.JSON() is wrong, it should be all lowercased... res.json()
  6. The FileReader is considered legacy so you no longer need it... use await blob.text() instead

here are two examples of how to read 1 remote file using fetch

// 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()

...and another with a actual local file selected from a user input

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">

  • Related