Tuesday, July 25, 2017

Awesome Way To Upload Multiple File

Ohsomedevs - Multiple file upload using PHP and JS.

Most of the time, we might find ourselves wanting to upload files more than one at a time. Though in some cases, it depends on how you would use file uploads. For some cases, like uploading your profile picture on a social media site, it's not appropriate of having a multiple file upload for uploading a single image, but it depends on your flow your website though.



Another case is there are some website uses multiple "file" input elements which is a bit annoying because you'll need to add and click the element if you're uploading a new file. And we know we hate this kind of issue and can not imagine how annoyed users would be. But luckily, with our current updated browser nowadays, they've implemented a method on which users can do multiple upload using a single input element.

So in this tutorial, we'll be guiding you on how to do a simple multiple file upload using JavaScript, for handling the file data on the DOM, and PHP, for processing the received file.


Let's start with the HTML:

  • No Files Selected



More importantly, the form's enctype value must be "multipart/form-data" .


As you can see, we just simply add a "multiple" attribute in the input element. The "multiple" attribute allows multiple file upload within a single input element.


File Input element with multiple attribute for allowing multiple upload.


Next step is to create a JS function which will list the filenames of the uploaded file:




On the script above, input.files property provides an array of files having the length of total files uploaded. Basic step is to loop through each file and access its data like file paths and name.



Now, the code above doesn't upload YET. You will need to handle the sent data from the JavaScript and let PHP process the received data file.

// PHP Script 
if(count($_FILES['uploads']['filesToUpload'])) {
 foreach ($_FILES['uploads']['filesToUpload'] as $file) {
  //do your upload stuff here
  echo $file;
 }
}



On the back-end side, the PHP creates an array of the uploaded files with the given input's name value. Input field with multiple attribute on it will always be considered as an array by PHP.

PHP multiple file uploading preview screenshot.
PHP file upload screenshot after finishing php process on uploading the file.

There you have it! Multiple file uploads is very helpful to avoid you users being annoyed and to ease up the process for uploading file. Uploading multiple file has been very helpful to other developers out there so you should try it now!.




No comments:

Post a Comment

PHP IMAP - Get Emails from GMAIL

Fetching emails from your GMIAL account is easier than what you expected. With the use of PHP IMAP Extension, you can easily fetch your e...