Quick Introduction

What’s the most boring thing in the world? The answer is chrome defaults. Just kidding! One of those default buttons is the choose file button.

I personally feel that button looks crappy and as a web developer it’s our job to make things look good over the internet.

So in this post, we will override that button and make our own custom file upload button which will look much better than the default. That button will also give us a preview of the selected image.

And all this is done using vanilla javascript and css, no server-side code needed.

If you are looking for Html grid templates: Read this post

Working

Local File Upload And Image Preview In Javascript[Code] 1 » Csspoint101

The logic behind file upload is very simple first, we will create the default choose file button by using <input type="file"> and then override with our custom button by hiding the default button.

And for image preview, we will use FileReader() method and readAsDataURL() that converts the image into the base64 string URL and use that to display image on the browser.

Here’s what we are making(Local File Upload):

file upload with javascript

Code Explanation:

Basic HTML

<!-- Container Markup -->
    <div class="container">
      <!-- Input Markup -->
      <input type="file" id="default-file" hidden="hidden" />

      <!-- Button Markup -->
      <button id="custom-btn" type="button" class="btn">
        CHOOSE FILE
      </button>
      <!-- Choose File TEXT Markup -->
      <span id="custom-space"> <strong> No</strong> File, Selected!😭</span>
    </div>
    <!-- Image Preview Markup -->
    <div class="preview_holder">
      <div id="preview">
        <img src="" id="preview_img" class="preview_img" />
        <span id="preview_text" class="preview_text">Image Preview</span>
      </div>
    </div>

This is basic HTML for our project. Container class is used to center the whole project and made it responsive.

<input type="file" id="default-file" hidden="hidden"/> It is the most important part of the project because this creates a default choose file button. When you specify type= "file" it converts the input block to choose the file button. And it is initially hidden because we will create our custom button.

custom-space class is just used to show if any file is selected or not. preview_holder is the class for the image preview section.

Basic CSS

/* General Styling */
body {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  background-color: rgb(20, 19, 19);
  color: white;
  font-family: "Montserrat", sans-serif;
}

/* Button Styling */
.btn {
  border: none;
  background-color: rgb(65, 174, 236);
  border-radius: 30px;
  padding: 10px 20px;
  cursor: pointer;
}

.btn:hover {
  opacity: 0.8;
  transition: all 500ms ease;
}

This is basic CSS which sets box-sizing to border-box and removes border and padding. Then I have done some basic styling for button.

Container CSS

/* Span Text Styling */
#custom-space {
  color: rgba(245, 245, 245, 0.678);
  margin-left: 2%;
}

/* Container Styling */
.container {
  display: flex;
  justify-content: center;
  margin-top: 8%;
}

This block just adds styling to text and .container class is given display:flex to center everything in the center.

Image Preview CSS

/* Image Preview Styling */
.preview_holder {
  margin-top: 4%;
  display: flex;
  align-items: center;
  justify-content: center;
}
#preview {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 400px;
  min-height: 300px;
  border: dotted;
}
.preview_img {
  display: none;
  width: 100%;
  object-fit: cover;
}

This block of code just adds styling to the image preview section. And initially, it is display:none and we make it display: block with javascript when any image selected.

Javascript Logic

// Grabbing Elements and Storing in Variables
const defaultFile = document.getElementById("default-file");
const customBtn = document.getElementById("custom-btn");
const customSpace = document.getElementById("custom-space");

In this block of code we are just gradding element and storing it an variable.

customBtn.addEventListener("click", function () {
  defaultFile.click();
});

This block of code is very crucial because this only triggers click function on our button and open choose file option in our browser.

// File Upload
defaultFile.addEventListener("change", function () {
  //  Format Selected File Text
  if (defaultFile.value) {
    customSpace.innerHTML =
      defaultFile.value.match(/[\/\\]([\w\d\s\.\-\(\)]+)$/)[1] + "🔥";
  } else {
    customSpace.innerHTML = "No File, Selected!😭";
  }

This function is triggered every time when someone clicks choose file button. And if it gets any file it will select its name and display on no file, selected space. When no file is selected then it will show No File, Selected!😭

defaultFile.value.match(/\/\$/)[1] + "🔥"; This block of code(regex code) filters only the file name and removes the whole file directory location. If you will not include this it will show the whole directory location along with the name.


  // Image Preview
  const files = defaultFile.files[0]; //files[0] - For getting first file
  //   console.log(files);

  if (files) {
    // Showing Image and Hiding "Image Preview" Text
    preview_img.style.display = "block";
    preview_text.style.display = "none";
    //Read File
    const fileReader = new FileReader();

    fileReader.addEventListener("load", function () {
      // convert image to base64 encoded string
      preview_img.setAttribute("src", this.result);
      console.log(this.result);
    });
    fileReader.readAsDataURL(files);
  }

const files = defaultFile.files[0]; .files is a method that returns the local file details.

Local File Upload And Image Preview In Javascript[Code] 2 » Csspoint101
Output of console.log(files)

const fileReader = new FileReader(); FileReader object lets web applications asynchronously read the contents of files. It returns fileList when it is .files. We will use selected file details and convert them to base64 string by readAsDataURL() method and then display as an image.

preview_img.setAttribute("src", this.result); On a load of file selection, this function triggers that set “src” attribute with this.result. You must be wondering what the hell is this.result. It returns the base64 String of the selected image.

file upload console.log
Output of this.result
fileReader.readAsDataURL(files);

The readAsDataURL method is used to read the contents of the specified file. This block of code just reads that base64 string and adds to the image holder space.

Thanks for reading my article on Local File Upload and Image Preview with javascript. If you liked these project-based posts, do share with others. Also, check out other posts on- Best Gatsby Plugins[2020] or Cool 3D Card Stacking Animation  and Awesome Liquid Distortion Effect

Default image
JatinRaj
Hello, My name is Jatin Raj and I am a web developer from India. I love to code every single day and share my thoughts with you people. Hobbies include reading books, football, and sketching/Painting.