JavaScript File & FileReader API 📂
JavaScript’s File API and FileReader API allow web applications to read, preview, and process files (e.g., images, text, PDFs) selected by users. These APIs are commonly used for file uploads, image previews, and text file reading.
1. Selecting a File Using <input type="file">
Example: Get File Details
🔹 event.target.files[0]
gives access to the first selected file.
🔹 Supports multiple files if multiple
is added to <input>
.
2. Reading a File Using FileReader
The FileReader
API reads files as text, data URL (for images), or binary data.
Example: Read a File as Text
🔹 readAsText(file)
reads the file and triggers onload
when done.
3. Display Image Preview Before Upload
Example: Show Image Preview
🔹 readAsDataURL(file)
converts the image into a Base64-encoded string.
4. Reading Binary Data (ArrayBuffer & Blob)
Example: Read a File as Binary
🔹 readAsArrayBuffer(file)
reads the file as raw binary data.
5. Drag & Drop File Upload
Example: Drag and Drop File Reader
🔹 event.dataTransfer.files[0]
retrieves the dropped file.
6. Upload File Using JavaScript (AJAX)
Example: Upload File to Server
🔹 FormData()
allows sending files via AJAX (fetch API).
🔹 Server-side (upload.php): Process uploaded file.
7. Summary of FileReader Methods
Method | Description |
---|---|
readAsText(file) | Reads file as plain text (UTF-8). |
readAsDataURL(file) | Converts file to Base64 string (for images). |
readAsArrayBuffer(file) | Reads file as raw binary data. |
readAsBinaryString(file) | Reads file as binary string (deprecated). |
🎯 Conclusion
✅ JavaScript's File API and FileReader API enable reading, previewing, and uploading files without reloading the page.
✅ Use cases: Text reading, image preview, drag & drop, AJAX uploads.
✅ Best practices: Check file.size
, file.type
, and handle errors properly.
🚀 Need help with file handling? Let me know! 📂