File Upload Card

Provide a modern and user-friendly interface for file uploads with this drag-and-drop card component.

This template is a must-have for any application that requires users to upload files. It provides users with the choice of browsing to the file or dragging files directly onto the drop zone.

Screenshot of a file upload card with a drag-and-drop interface.

Get Source Code Preview

About this Component

This is a functional front-end component powered by a snippet of vanilla JavaScript. The drop zone provides clear visual feedback to the user by changing its appearance when a file is dragged over it. While the component handles the client-side interaction, it would need to be connected to a server-side script to handle the actual file upload process.

Features

Code Breakdown

HTML Structure

The structure is very simple and robust. The visual component is a single label element with the class .file-drop-zone. This label acts as the entire card, the drop area, and the clickable trigger. The standard input type="file" is placed inside the label and is visually hidden by the CSS. By placing the input inside, it is implicitly associated with the label, ensuring that clicking anywhere on the card will open the file browser.

CSS Styling

A dashed border is used on the .file-drop-zone to give it the appearance of a placeholder. The JavaScript adds a class, .is-dragover, to this element when a file is being dragged over it. The CSS rule .file-drop-zone.is-dragover then targets this class to change the border style and background color, providing instant visual feedback to the user.

JavaScript Logic

The script adds several event listeners to the drop zone. The dragover and drop event listeners call event.preventDefault(), which is required to stop the browser from its default action of trying to open the dropped file. The dragover listener adds the .is-dragover class, while the dragleave listener removes it. The drop event listener accesses the dropped files via event.dataTransfer.files and assigns them to our hidden file input's files property, making it ready for a form submission or an API call.

Code

Here's the complete code. The front-end interaction is ready to use, but you will need to add your own back-end logic to handle the file processing once a user has selected or dropped their files.

View Output