Multiple file upload in bootstrap modal – PHP & MySQL

You are going to need a library called Bootstrap FD, you can get it from here. After downloading the library, extract the ZIP file and goto “dist” folder. Here you will find CSS and JS files, copy them in your project and include them in your header or footer. This library requires bootstrap and jQuery to be included in your project. If you have setup the bootstrap and jQuery, you can just use their CDN links rather than downloading.

<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="bootstrap.fd.css">
<script src="bootstrap.fd.js"></script>

First we have included the bootstrap CSS file, then jQuery and then bootstrap JS file. Because bootstrap JS also requires jQuery so you must include the jQuery before bootstrap JS. You can change the version number of CDN links if there is new version available.

Create a button which when clicked will call a function in Javascript. To open the bootstrap modal, we have to use the function $.FileDialog() and this will open the pop-up where you can drag and drop your files. You can also set options for this dialog, for example, whether you want the user to select only images files or all type of files etc.

<form>
	<button type="button" onclick="selectFiles();">
		Select files
	</button>

	<input type="submit">
</form>
<script>
	function selectFiles() {
		$.FileDialog({
			"accept": "image/*"
		});
	}
</script>

To preview the image files selected by user, just add a div tag and give it a unique ID.

<div id="selected-images"></div>

And change your $.FileDialog function to the following. “files.bs.filedialog” function will be called when user select the files and press “OK”. Create a global array which will hold all images. All selected images will be received in “event.files” array, so loop through it and push in that global array. Create a string variable which will hold the img tag HTML. In the same loop, we are creating an img tag and each object of “event.files” array contains a variable named “content” while contains the content of image. This can be used.

window.selectedImages = [];

$.FileDialog({
	"accept": "image/*"
}).on("files.bs.filedialog", function (event) {
	var html = "";
	for (var a = 0; a < event.files.length; a++) {
		selectedImages.push(event.files[a]);
		html += "<img src='" + event.files[a].content + "'>";
	}
	document.getElementById("selected-images").innerHTML += html;
});

To save these images on server, give your form a unique ID and attach an onsubmit event with it. We will be using FormData object to send all images and other form fields via AJAX. And onsubmit event will prevent the default behaviour of form. This will prevent the form from submitting and will call your javascript function. This function will create a new FormData object and append all images in it. Make sure to add brackets “[]” with images key so it will send all images as array. Otherwise, only the last selected image will be processed by server. Then it sends a neat AJAX request in Vanilla JS and attach the form data in it. After the server processed the files and send the response back to client, you will need to show some text to user or wants to redirect to different page. So in “onreadystatechange” event you can put all your code which needs to be executed once response is received from server.

<form id="form" onsubmit="return submitForm();">
function submitForm() {
	var form = document.getElementById("form");
	var formData = new FormData(form);

	for (var a = 0; a < selectedImages.length; a++) {
		formData.append("images[]", selectedImages[a]);
	}

	var ajax = new XMLHttpRequest();
	ajax.open("POST", "Http.php", true);
	ajax.send(formData);

	ajax.onreadystatechange = function () {
		if (this.readyState == 4 && this.status == 200) {
			console.log(this.responseText);
		}
	};

	return false;
}

Http.php

In this file, create a connection with your database (you might have already set up). Create a separate table where path of each image will be saved. Loop through all the images, insert them in database, and finally save the image file in your server. Create a new folder named “images” or any other of your choice, where all images will be stored. Timestamp is prepended with each image name just to make it unique. As you might have seen, if you download some image from facebook or whatsapp, it always has a different name no matter if that image is uploaded by another person.

<?php

$conn = mysqli_connect("localhost", "root", "", "tutorials");

for ($a = 0; $a < count($_FILES["images"]["name"]); $a++)
{
	$path = "images/" . time() . "-" . $_FILES["images"]["name"][$a];

	$sql = "INSERT INTO images(image_path) VALUES('$path')";
	mysqli_query($conn, $sql);

	move_uploaded_file($_FILES["images"]["tmp_name"][$a], $path);
}

echo "Done";

2 Replies to “Multiple file upload in bootstrap modal – PHP & MySQL”

Leave a Reply

Please disable your adblocker or whitelist this site!