1

I am creating a component to upload a file, such as:

<input onchange={handleFileUpload} />
function handleFileUpload(event) {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.onload = ev => uploadMyFile(ev.target.result):
    reader.readAsText(file);
}

event.target.files[0] returns a File object, which has basic information like the name, type and size. However, after inspecting the instance in the console and reading the MDN docs on Files and Blobs, I don't understand how my file can be read by reader.

Specifically, a File object doesn't seem to include a 'filepath' or a 'data' property; it would seem to me as if it only includes properties describing meta information on the file, but not its location in the local filesystem, or the actual data in some form.

How does the a FileReader now where to find the file to read, then?

alexcs
  • 480
  • 5
  • 16

1 Answers1

1

FileReader and File objects are not written in JavaScript. They expose certain data to JavaScript through APIs.

When FileReader needs to read a file via a File object, it does so through APIs that are not exposed to JS (they are internal APIs that are probably written in C).

You can't access that data at the JavaScript level because it isn't exposed there (either because it simply isn't needed or because it would be a security risk for websites to be able to access that data).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335