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 +

File Reader

+ +
+

+```
+
+#### JavaScript
+
+```js
+// Function to initialize the program
+function initializeApp() {
+  // Select HTML elements
+  const fileInput = document.getElementById("file-input");
+  const fileContentDisplay = document.getElementById("file-content");
+  const messageDisplay = document.getElementById("message");
+
+  // Add event listener to file input
+  fileInput.addEventListener("change", handleFileSelection);
+
+  // Handles file selection and reads its content
+  function handleFileSelection(event) {
+    const file = event.target.files[0];
+    fileContentDisplay.textContent = ""; // Clear previous file content
+    messageDisplay.textContent = ""; // Clear previous messages
+
+    // Validate file existence and type
+    if (!file) {
+      showMessage("No file selected. Please choose a file.", "error");
+      return;
+    }
+
+    if (!file.type.startsWith("text")) {
+      showMessage("Unsupported file type. Please select a text file.", "error");
+      return;
+    }
+
+    // Read the file
+    const reader = new FileReader();
+    reader.onload = () => {
+      fileContentDisplay.textContent = reader.result;
+    };
+    reader.onerror = () => {
+      showMessage("Error reading the file. Please try again.", "error");
+    };
+    reader.readAsText(file);
+  }
+
+  // Displays a message to the user
+  function showMessage(message, type) {
+    messageDisplay.textContent = message;
+    messageDisplay.style.color = type === "error" ? "red" : "green";
+  }
+}
+
+// Initialize the app when the DOM is fully loaded
+document.addEventListener("DOMContentLoaded", initializeApp);
+```
+
+### Result
+
+{{EmbedLiveSample("Examples", 640, 300)}}
+
 ## Events
 
 Listen to these events using {{domxref("EventTarget/addEventListener", "addEventListener()")}} or by assigning an event listener to the `oneventname` property of this interface. Remove the event listeners with {{domxref("EventTarget.removeEventListener", "removeEventListener()")}}, once `FileReader` is no longer used, to avoid memory leaks.