Bootstrap image upload
In today's Bootstrap snippet tutorial, I will show you how to create a Bootstrap Image Upload with an image preview.
In this example, I am going to create a page that lets users upload images. When you select an image from your local machine, it will be displayed in an upload preview overlay. we will be using the browser's built-in JavaScript FileReader.
How the image upload snippet works:
- Layout using Bootstrap 4 input group markup and Bootstrap utility classes. (If you are using Bootstrap 5, the syntax should work without any major issues)
- When the user selects the image to upload on his/her computer, JavaScript handles the Image preview and displays the file name.
- The Image preview part uses the browser's JavaScript FileReader
Why display preview images when handling file uploads?
The truth is that file uploads can be a bit of a pain. Not only does it take time for users to figure out how to do it, but there's also the issue of usability. If you don't have any visual cues, such as a progress bar or any other indicator, then the user has no idea what's going on.
Luckily for us (and our users), there are ways we can make this process easier and more intuitive. One way is by providing a preview image when handling file uploads.
How to handle the backend of the form?
Even though, as I focus only on the front-end part in this snippet, you might be wondering how to take care of the backend part. I will definitely be writing another more in-depth tutorial on this popular issue, but meanwhile, let's have a look at what others have written on this topic.
Just to outline the easiest process in PHP:
-
after submitting the form, you will have your file in the
$_FILES
global variable. If you called your input <input name="image_upload">, then all its characteristics will be accessible in$_FILES['image_upload']
-
you can then simply move the uploaded file to the desired location using the move_uploaded_file function. E.g.
move_uploaded_file($_FILES['the_file']['tmp_name'], $uploadDirectory . basename($_FILES['the_file']['name']) )
Alright, let's have a look at the snippet!
If you liked this snippet, you might also enjoy exploring Bootstrap Calendar or Bootstrap list .