0

I have two inputs: type="file" and type="url". Thus the user has the possibility to provide either a local file or a remote file. In any case, after reading the file, the text should be processed by the same function func.

I already used fetch. However, fetch cannot handle local files (e.g. Fetch request to local file not working). Thus a combination with FileReader is the next idea. But FileReader is not async; a work around was suggested here.

But are there better way to handle this common situation?

laconbass
  • 17,080
  • 8
  • 46
  • 54
  • What are you intending on doing with the files? You have to get a server involved though to avoid CORS - a server can download any public url pretty easily, but be mindful of the attack vectors that open up when somebody can ask a server to download any given URL. – Luke Briggs Jul 19 '21 at 00:07
  • I'm interested in plotting remote or local data files. Some files can be still retrieved, e.g. `fetch('https://raw.githubusercontent.com/plotly/datasets/master/spectral.csv').then(d => d.text()).then(console.log)`. – Friedrich -- Слава Україні Jul 19 '21 at 00:16
  • if fetch could get local files from an online origin.. then any webpage could literally look into your files.. I mean that's not exactly *private* – The Bomb Squad Jul 19 '21 at 01:46
  • " But FileReader is not async" — Yes, it is. It doesn't return a promise, but it is asynchronous. (It can't just return a promise as it supports things like incremental reading which aren't a straight forward "success/fail" with nothing else. – Quentin Jul 19 '21 at 07:47
  • It is a pity that this question was closed. The "duplicate" link does not help me. It uses neither fetch nor FileReader. I understand that callback is needed in both cases. Also my question is not about CORS. Even if the url is on the same domain, the problem remains. – Friedrich -- Слава Україні Jul 19 '21 at 08:29
  • I realised in https://stackoverflow.com/a/59804354/11769765 that `FileReader` has the `.text()` method, too, as `fetch`! Thus no extra `Promise` wrapper is needed. Just `async function readfile(path) {file = (path instanceof File)? path : (await fetch(path)); return await file.text()}` will do the job and handle both cases: `readfile('https://raw.githubusercontent.com/plotly/datasets/master/spectral.csv').then(console.log)`. Similar a local file could be passed as file object from `input type=file`. A much easier solution than the suggested "duplicate". – Friedrich -- Слава Україні Jul 19 '21 at 19:50

0 Answers0