Published on

6 Easy Ways To Build A Multiple File Upload With JS With Tailwind CSS

Tags
Multiple file upload with JS

What is Tailwind CSS?

Tailwind CSS is a utility-first CSS framework that helps developers to create responsive and customizable user interfaces with ease. It provides a set of pre-defined CSS classes that can be used to style HTML elements. Tailwind CSS is gaining popularity among developers due to its simplicity and flexibility.

The description of Multiple file upload with JS ui component

Multiple file upload with JS ui component is a user interface element that allows users to select and upload multiple files at once. It is a common feature in web applications that require users to upload files such as images, videos, and documents. The multiple file upload with JS ui component can be implemented using various JavaScript libraries such as Dropzone.js, Fine Uploader, and Uppy.

Why use Tailwind CSS to create a Multiple file upload with JS ui component?

Tailwind CSS provides a set of pre-defined CSS classes that can be used to style HTML elements. This makes it easy to create a custom and responsive user interface for the multiple file upload with JS ui component. Tailwind CSS also provides a set of utility classes that can be used to modify the appearance of the UI component on the fly. This makes it easy to create a dynamic and interactive user interface.

The preview of Multiple file upload with JS ui component

To create a multiple file upload with JS ui component using Tailwind CSS, we can use the Dropzone.js library. Dropzone.js is a lightweight and easy-to-use JavaScript library that provides drag and drop file uploads with image previews. Here is a preview of what the multiple file upload with JS ui component using Dropzone.js and Tailwind CSS looks like:

Free download of the Multiple file upload with JS's source code

The source code of Multiple file upload with JS ui component

To create a multiple file upload with JS ui component using Dropzone.js and Tailwind CSS, we need to include the necessary JavaScript and CSS files. Here is the source code for the multiple file upload with JS ui component:

<div class="w-full h-screen bg-white">
    <div class="container mx-auto h-full flex flex-col justify-center items-center">
        <div id="images-container"></div>
        <div class="flex w-full justify-center">
            <div id="multi-upload-button"
                 class="inline-flex items-center px-4 py-2 bg-gray-600 border border-gray-600 rounded-l font-semibold cursor-pointer text-sm text-white tracking-widest hover:bg-gray-500 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:ring focus:ring-gray-300 disabled:opacity-25 transition ">
                Click to browse
            </div>
            <div class="w-4/12 lg:w-3/12 border border-gray-300 rounded-r-md flex items-center justify-between">
                <span id="multi-upload-text" class="p-2"></span>
                <button id="multi-upload-delete" class="hidden" onclick="removeMultiUpload()">
                    <svg xmlns="http://www.w3.org/2000/svg" class="fill-current text-red-700 w-3 h-3"
                         viewBox="0 0 320 512">
                        <path
                                d="M310.6 361.4c12.5 12.5 12.5 32.75 0 45.25C304.4 412.9 296.2 416 288 416s-16.38-3.125-22.62-9.375L160 301.3L54.63 406.6C48.38 412.9 40.19 416 32 416S15.63 412.9 9.375 406.6c-12.5-12.5-12.5-32.75 0-45.25l105.4-105.4L9.375 150.6c-12.5-12.5-12.5-32.75 0-45.25s32.75-12.5 45.25 0L160 210.8l105.4-105.4c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25l-105.4 105.4L310.6 361.4z"/>
                    </svg>
                </button>
            </div>
        </div>
        <input type="file" id="multi-upload-input" class="hidden" multiple/>
    </div>
</div>

<script>
    //all ids and some classes are importent for this script

    multiUploadButton = document.getElementById("multi-upload-button");
    multiUploadInput = document.getElementById("multi-upload-input");
    imagesContainer = document.getElementById("images-container");
    multiUploadDisplayText = document.getElementById("multi-upload-text");
    multiUploadDeleteButton = document.getElementById("multi-upload-delete");

    multiUploadButton.onclick = function () {
        multiUploadInput.click(); // this will trigger the click event
    };

    multiUploadInput.addEventListener('change', function (event) {

        if (multiUploadInput.files) {
            let files = multiUploadInput.files;

            // show the text for the upload button text filed
            multiUploadDisplayText.innerHTML = files.length + ' files selected';

            // removes styles from the images wrapper container in case the user readd new images
            imagesContainer.innerHTML = '';
            imagesContainer.classList.remove("w-full", "grid", "grid-cols-1","sm:grid-cols-2","md:grid-cols-3","lg:grid-cols-4", "gap-4");

            // add styles to the images wrapper container
            imagesContainer.classList.add("w-full", "grid", "grid-cols-1","sm:grid-cols-2","md:grid-cols-3","lg:grid-cols-4", "gap-4");

            // the delete button to delete all files
            multiUploadDeleteButton.classList.add("z-100", "p-2", "my-auto");
            multiUploadDeleteButton.classList.remove("hidden");

            Object.keys(files).forEach(function (key) {

                let file = files[key];

                // the FileReader object is needed to display the image
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function () {

                    // for each file we create a div to contain the image
                    let imageDiv = document.createElement('div');
                    imageDiv.classList.add("h-64", "mb-3", "w-full", "p-3", "rounded-lg", "bg-cover", "bg-center");
                    imageDiv.style.backgroundImage = 'url(' + reader.result + ')';
                    imagesContainer.appendChild(imageDiv);
                }
            })
        }
    })

    function removeMultiUpload() {
        imagesContainer.innerHTML = '';
        imagesContainer.classList.remove("w-full", "grid", "grid-cols-1","sm:grid-cols-2","md:grid-cols-3","lg:grid-cols-4", "gap-4");
        multiUploadInput.value = '';
        multiUploadDisplayText.innerHTML = '';
        multiUploadDeleteButton.classList.add("hidden");
        multiUploadDeleteButton.classList.remove("z-100", "p-2", "my-auto");
    }
</script>

How to create a Multiple file upload with JS with Tailwind CSS?

Here are the 6 easy steps to create a multiple file upload with JS with Tailwind CSS:

Step 1: Include the necessary files

To use Dropzone.js and Tailwind CSS, we need to include the necessary JavaScript and CSS files. We can do this by adding the following code to the head section of our HTML file:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/dropzone.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/dropzone.js"></script>

Step 2: Create the HTML markup

Next, we need to create the HTML markup for the multiple file upload with JS ui component. We can do this by adding the following code to our HTML file:

<div class="w-full max-w-md mx-auto">
  <form action="/file-upload" class="dropzone" id="my-awesome-dropzone"></form>
</div>

Step 3: Initialize Dropzone.js

After creating the HTML markup, we need to initialize Dropzone.js. We can do this by adding the following code to our JavaScript file:

Dropzone.options.myAwesomeDropzone = {
  paramName: "file", // The name that will be used to transfer the file
  maxFilesize: 2, // MB
  addRemoveLinks: true,
  dictDefaultMessage: "Drag and drop files here or click to upload",
  dictRemoveFile: "Remove",
  acceptedFiles: ".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.zip,.rar",
  init: function() {
    this.on("success", function(file, response) {
      console.log(response);
    });
  }
};

Step 4: Customize the appearance

To customize the appearance of the multiple file upload with JS ui component, we can use Tailwind CSS utility classes. Here is an example of how we can customize the appearance:

<div class="w-full max-w-md mx-auto">
  <form action="/file-upload" class="dropzone flex flex-col items-center justify-center border-2 border-dashed border-gray-400 rounded-lg p-10">
    <div class="text-gray-600 mb-4">Drag and drop files here or click to upload</div>
    <div class="fallback">
      <input name="file" type="file" multiple />
    </div>
  </form>
</div>

Step 5: Handle file uploads

To handle file uploads, we can use the Dropzone.js events. Here is an example of how we can handle file uploads:

Dropzone.options.myAwesomeDropzone = {
  paramName: "file", // The name that will be used to transfer the file
  maxFilesize: 2, // MB
  addRemoveLinks: true,
  dictDefaultMessage: "Drag and drop files here or click to upload",
  dictRemoveFile: "Remove",
  acceptedFiles: ".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.zip,.rar",
  init: function() {
    this.on("success", function(file, response) {
      console.log(response);
    });
  }
};

Step 6: Handle file removals

To handle file removals, we can use the Dropzone.js events. Here is an example of how we can handle file removals:

Dropzone.options.myAwesomeDropzone = {
  paramName: "file", // The name that will be used to transfer the file
  maxFilesize: 2, // MB
  addRemoveLinks: true,
  dictDefaultMessage: "Drag and drop files here or click to upload",
  dictRemoveFile: "Remove",
  acceptedFiles: ".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.zip,.rar",
  init: function() {
    this.on("success", function(file, response) {
      console.log(response);
    });
    this.on("removedfile", function(file) {
      console.log(file);
    });
  }
};

Conclusion

In conclusion, creating a multiple file upload with JS with Tailwind CSS is easy and straightforward. By using Dropzone.js and Tailwind CSS, we can create a custom and responsive user interface for the multiple file upload with JS ui component. With the 6 easy steps outlined in this article, you can create a multiple file upload with JS with Tailwind CSS in no time.