Reading file contents on the client-side in javascript in various browsers

后端 未结 4 891
南旧
南旧 2020-11-22 06:45

I\'m attempting to provide a script-only solution for reading the contents of a file on a client machine through a browser.

I have a solution that works with Firefox

4条回答
  •  鱼传尺愫
    2020-11-22 07:15

    There's a modern native alternative: File implements Blob, so we can call Blob.text().

    async function readText(event) {
      const file = event.target.files.item(0)
      const text = await file.text();
      
      document.getElementById("output").innerText = text
    }
    
    

    Currently (September 2020) this is supported in Chrome and Firefox, for other Browser you need to load a polyfill, e.g. blob-polyfill.

提交回复
热议问题