File and FileReader

File and FileReader

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

<input type="file" id="fileInput"> <script> document.getElementById("fileInput").addEventListener("change", function(event) { let file = event.target.files[0]; // Get the first selected file console.log(`Name: ${file.name}`); console.log(`Size: ${file.size} bytes`); console.log(`Type: ${file.type}`); }); </script>

🔹 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

document.getElementById("fileInput").addEventListener("change", function(event) { let file = event.target.files[0]; let reader = new FileReader(); reader.onload = function(e) { console.log("File Content:", e.target.result); // Logs file text content }; reader.readAsText(file); // Reads file as plain text });

🔹 readAsText(file) reads the file and triggers onload when done.

3. Display Image Preview Before Upload

Example: Show Image Preview

<input type="file" id="imageInput" accept="image/*"> <img id="preview" width="200"> <script> document.getElementById("imageInput").addEventListener("change", function(event) { let file = event.target.files[0]; let reader = new FileReader(); reader.onload = function(e) { document.getElementById("preview").src = e.target.result; // Set image src }; reader.readAsDataURL(file); // Convert to Base64 URL }); </script>

🔹 readAsDataURL(file) converts the image into a Base64-encoded string.

4. Reading Binary Data (ArrayBuffer & Blob)

Example: Read a File as Binary

document.getElementById("fileInput").addEventListener("change", function(event) { let file = event.target.files[0]; let reader = new FileReader(); reader.onload = function(e) { let arrayBuffer = e.target.result; // Binary data console.log(new Uint8Array(arrayBuffer)); // Convert to Uint8Array }; reader.readAsArrayBuffer(file); // Read as binary });

🔹 readAsArrayBuffer(file) reads the file as raw binary data.

5. Drag & Drop File Upload

Example: Drag and Drop File Reader

<div id="dropZone" style="border: 2px dashed #333; padding: 20px;">Drop files here</div> <script> let dropZone = document.getElementById("dropZone"); dropZone.addEventListener("dragover", function(event) { event.preventDefault(); // Allow drop }); dropZone.addEventListener("drop", function(event) { event.preventDefault(); let file = event.dataTransfer.files[0]; // Get dropped file let reader = new FileReader(); reader.onload = function(e) { console.log("Dropped File Content:", e.target.result); }; reader.readAsText(file); }); </script>

🔹 event.dataTransfer.files[0] retrieves the dropped file.

6. Upload File Using JavaScript (AJAX)

Example: Upload File to Server

document.getElementById("fileInput").addEventListener("change", function(event) { let file = event.target.files[0]; let formData = new FormData(); formData.append("file", file); fetch("upload.php", { method: "POST", body: formData }) .then(response => response.text()) .then(data => console.log("Upload Success:", data)) .catch(error => console.error("Upload Error:", error)); });

🔹 FormData() allows sending files via AJAX (fetch API).
🔹 Server-side (upload.php): Process uploaded file.

7. Summary of FileReader Methods

MethodDescription
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! 📂

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close