Skip to content

Commit a54ef0a

Browse files
Enhance FileReader documentation with security details and add usage examples (mdn#36443)
1 parent 3b15ee8 commit a54ef0a

File tree

1 file changed

+74
-1
lines changed

1 file changed

+74
-1
lines changed

files/en-us/web/api/filereader/index.md

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ The **`FileReader`** interface lets web applications asynchronously read the con
1111

1212
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.
1313

14-
`FileReader` can only access the contents of files that the user has explicitly selected, either using an HTML `<input type="file">` 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.
14+
**`FileReader`** is designed to read the contents of files that the user has explicitly selected through an HTML `<input type="file">` 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.
15+
16+
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.
1517

1618
{{InheritanceDiagram}}
1719

@@ -52,6 +54,77 @@ See [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files
5254
- {{domxref("FileReader.readAsText()")}}
5355
- : 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.
5456

57+
## Examples
58+
59+
### File Reader
60+
61+
This example reads and displays the contents of a text file directly in the browser.
62+
63+
#### HTML
64+
65+
```html
66+
<h1>File Reader</h1>
67+
<input type="file" id="file-input" />
68+
<div id="message"></div>
69+
<pre id="file-content"></pre>
70+
```
71+
72+
#### JavaScript
73+
74+
```js
75+
// Function to initialize the program
76+
function initializeApp() {
77+
// Select HTML elements
78+
const fileInput = document.getElementById("file-input");
79+
const fileContentDisplay = document.getElementById("file-content");
80+
const messageDisplay = document.getElementById("message");
81+
82+
// Add event listener to file input
83+
fileInput.addEventListener("change", handleFileSelection);
84+
85+
// Handles file selection and reads its content
86+
function handleFileSelection(event) {
87+
const file = event.target.files[0];
88+
fileContentDisplay.textContent = ""; // Clear previous file content
89+
messageDisplay.textContent = ""; // Clear previous messages
90+
91+
// Validate file existence and type
92+
if (!file) {
93+
showMessage("No file selected. Please choose a file.", "error");
94+
return;
95+
}
96+
97+
if (!file.type.startsWith("text")) {
98+
showMessage("Unsupported file type. Please select a text file.", "error");
99+
return;
100+
}
101+
102+
// Read the file
103+
const reader = new FileReader();
104+
reader.onload = () => {
105+
fileContentDisplay.textContent = reader.result;
106+
};
107+
reader.onerror = () => {
108+
showMessage("Error reading the file. Please try again.", "error");
109+
};
110+
reader.readAsText(file);
111+
}
112+
113+
// Displays a message to the user
114+
function showMessage(message, type) {
115+
messageDisplay.textContent = message;
116+
messageDisplay.style.color = type === "error" ? "red" : "green";
117+
}
118+
}
119+
120+
// Initialize the app when the DOM is fully loaded
121+
document.addEventListener("DOMContentLoaded", initializeApp);
122+
```
123+
124+
### Result
125+
126+
{{EmbedLiveSample("Examples", 640, 300)}}
127+
55128
## Events
56129

57130
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.

0 commit comments

Comments
 (0)