Just Learn Code

Mastering File Uploads with JavaScript’s FileReader API

Introduction to the JavaScript FileReader API

In today’s digital world, file handling is a fundamental task for developers. There may be times when you need to work with files purely on the client side.

This is where the JavaScript FileReader API comes in handy. The FileReader API is a method that allows web developers to read file content from a user’s computer.

It allows files to be read asynchronously, which means the file can be read without disturbing the page’s normal functionality. In this article, we will explore the basics of the JavaScript FileReader API, including the File object, the FileList object, and the different methods of the FileReader object.

File Object and FileList Object

We cannot proceed without first understanding what files, File, and FileList is. The File object is a wrapper object to represent files and their content, whereas, the FileList object is a collection of File objects returned by an HTML input element.

Let us consider how to access the images’ File Object using the HTML input element below:

“`html

“`

We can gain access to the File object by querying the `files` property of this HTML input element. “`javascript

let fileInput = document.getElementById(“file-input”);

let file = fileInput.files[0];

“`

The above code assigns the first uploaded image file to the `file` variable.

To access all uploaded image files at once, we use the FileList, as shown below:

“`javascript

let fileInput = document.getElementById(“file-input”);

let files = fileInput.files;

for (let i = 0; i < files.length; i++) {

console.log(files[i]);

}

“`

Here, the for loop takes care of accessing all the uploaded image files.

The Methods of the FileReader Object

After accessing the File and FileList object, the next step is to read the files. FileReader comes with different methods to read uploaded files.

The following are examples of the FileReader methods:

readAsDataURL():

This method converts the image file into base64-encoded string format, as shown below:

“`javascript

let reader = new FileReader();

if (file) {

reader.readAsDataURL(file);

}

“`

readAsText():

This method returns the file in a string format.

“`javascript

let reader = new FileReader();

if (file) {

reader.readAsText(file);

}

“`

readAsBinaryString():

This method returns the file in binary string format.

“`javascript

let reader = new FileReader();

if (file) {

reader.readAsBinaryString(file);

}

“`

readAsArrayBuffer():

This method returns the file in binary format. “`javascript

let reader = new FileReader();

if (file) {

reader.readAsArrayBuffer(file);

}

“`

Using JavaScript FileReader to Implement an Image Upload Application

Now that we have an understanding of the FileReader API fundamentals, we can proceed to build a simple drag-and-drop image upload application using vanilla JavaScript.

Setting up Project Structure

The project structure is crucial for any application. Ensure that you create a clean project structure before proceeding to the next step.

In this example, we would be creating a simple HTML, CSS, and JavaScript file. Handling Drag & Drop and File Input Events

The next step in building the image upload application is handling the Drag & Drop and File Input events.

The code below shows how to implement Drag & Drop:

“`javascript

let dropzone = document.getElementById(“dropzone”);

dropzone.addEventListener(“dragenter”, dragEnter, false);

dropzone.addEventListener(“dragover”, dragOver, false)

dropzone.addEventListener(“dragleave”, dragLeave, false);

dropzone.addEventListener(“drop”, handleDrop, false);

function dragEnter(e) {

e.preventDefault();

e.stopPropagation();

}

function dragOver(e) {

e.preventDefault();

e.stopPropagation();

}

function dragLeave(e) {

e.preventDefault();

e.stopPropagation();

}

function handleDrop(e) {

e.preventDefault();

e.stopPropagation();

let files = e.dataTransfer.files;

handleImages(files);

}

“`

The `dragenter`, `dragover`, `dragleave`, and `drop` events determine the entire Drag & Drop procedure. They specify how the Drag & Drop mechanism should function, and we can customize their functionalities as we please.

In the same vein, we can handle the file input as shown below:

“`javascript

let fileInput = document.getElementById(“file-input”);

fileInput.addEventListener(“change”, (e) => {

let files = e.target.files;

handleImages(files);

});

“`

Here, the `change` event is responsible for handling every file selected through file input.

Handling Uploaded Images

After reading the uploaded image file(s), we can then display the image(s) on the web page. The `handleImages` function below handles this:

“`javascript

function handleImages(files) {

for (let i = 0; i < files.length; i++) {

let file = files[i];

if (validImage(file.type)) {

let reader = new FileReader();

reader.onload = function (event) {

let imgWrapper = document.createElement(“div”);

imgWrapper.classList.add(“img-wrapper”);

let img = document.createElement(“img”);

img.src = event.target.result;

let size = document.createElement(“span”);

size.innerText = formatBytes(file.size);

imgWrapper.append(img, size);

document.getElementById(“display”).appendChild(imgWrapper);

}

reader.readAsDataURL(file);

}

}

}

“`

The `validImage` function accepts a file’s MIME type to check if it is an image file.

We display the image wrapper element, image element, and the image size element in the HTML to produce a view of every uploaded image.

Uploading Images Using Fetch API and Server-Side Script

Finally, we upload the image file(s) to our server using the Fetch API and server-side script. The implementation may differ based on server-side scripting languages like PHP, Python, or Node.js.

We would be using PHP as an example in this tutorial. “`javascript

function uploadImages() {

let files = document.getElementById(“file-input”).files;

let formData = new FormData();

for (let i = 0; i < files.length; i++) {

let file = files[i];

if (valid(file.type)) {

// Append file data to form data

formData.append(“file[]”, file);

}

}

fetch(“upload.php”, {

method: “POST”,

body: formData

})

.then(response => response.json())

.then(response => console.log(response))

.catch(error => console.error(error));

}

“`

Here, `formData` is used to collect all image files, which would be sent to the server via Fetch API.

The “upload.php” script on the server-side receives the image files uploaded to the server, a response from the server is sent back to the application. This response can be anything from an error message, success message, or a JSON object containing any number of properties.

Final Words

This tutorial provides a basic foundation for building an image upload application using JavaScript FileReader API. We have explored basic file handling concepts, drag and drop functionality, file input, formatting image size, and uploading files to a server using Fetch API.

As you may have observed, the JavaScript FileReader API provides an efficient way for developers to handle file uploads on the client side. The JavaScript FileReader API is an essential tool for developers who need to handle file uploads on the client side.

This article has provided a comprehensive guide to using the FileReader API to build an image upload application, covering essential concepts such as the File and FileList objects, FileReader methods, drag and drop functionality, and uploading images to a server using Fetch API. By following the guidelines presented, developers can build an efficient image upload application using vanilla JavaScript.

The takeaway from this article emphasizes the importance of understanding the fundamentals of the FileReader API and its potential uses for different file types beyond image files.

Popular Posts