From a54ef0af74d12df909b4a804534aa7d545c036ac Mon Sep 17 00:00:00 2001 From: Alexander John <96aljohn@gmail.com> Date: Wed, 8 Jan 2025 16:42:30 -0800 Subject: [PATCH] Enhance FileReader documentation with security details and add usage examples (#36443) --- files/en-us/web/api/filereader/index.md | 75 ++++++++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/files/en-us/web/api/filereader/index.md b/files/en-us/web/api/filereader/index.md index e8a11c448608596..79fc77f449d1aaa 100644 --- a/files/en-us/web/api/filereader/index.md +++ b/files/en-us/web/api/filereader/index.md @@ -11,7 +11,9 @@ The **`FileReader`** interface lets web applications asynchronously read the con File objects may be obtained from a {{domxref("FileList")}} object returned as a result of a user selecting files using the {{HTMLElement("input")}} element, or from a drag and drop operation's {{domxref("DataTransfer")}} object. -`FileReader` can only access the contents of files that the user has explicitly selected, either using an HTML `` element or by drag and drop. It cannot be used to read a file by pathname from the user's file system. To read files on the client's file system by pathname, use the [File System Access API](/en-US/docs/Web/API/File_System_API). To read server-side files, use {{domxref("Window/fetch", "fetch()")}}, with [CORS](/en-US/docs/Web/HTTP/CORS) permission if reading cross-origin. +**`FileReader`** is designed to read the contents of files that the user has explicitly selected through an HTML `` element or by drag-and-drop interactions. It works with a {{domxref("File")}} object, which the browser securely provides when the user selects a file. **`FileReader`** cannot access files directly using a pathname (e.g., `/home/john-doe/documents/file.txt`), as it does not have unrestricted access to the user's file system for security reasons. + +If you need to access files directly by pathname on the user's local file system, you can use the [File System Access API](/en-US/docs/Web/API/File_System_API), which requires explicit user permission. For accessing files located on a server, you can use {{domxref("Window/fetch", "fetch()")}} with [CORS](/en-US/docs/Web/HTTP/CORS) permission if reading cross-origin resources or other server-side tools like {{Glossary("Node.js")}}. The **`FileReader`** interface ensures secure, user-consented access to file content in web applications. {{InheritanceDiagram}} @@ -52,6 +54,77 @@ See [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files - {{domxref("FileReader.readAsText()")}} - : Starts reading the contents of the specified {{domxref("Blob")}}, once finished, the `result` attribute contains the contents of the file as a text string. An optional encoding name can be specified. +## Examples + +### File Reader + +This example reads and displays the contents of a text file directly in the browser. + +#### HTML + +```html +