This is an excerpt from the HTML5 Solutions: Essential Techniques for HTML5 Developers book by Apress (where I'm one of the author).
It was already possible to send any kind of file from your computer to a remote server with the older
versions of HTML by using the form, and the <input type = file> in particular.
This form control, however, had the limit of being able to send only one file at a time. If the user wanted to
upload a photo album and thus send several photos, the developer had to use other technologies, such as
Flash or JavaScript, to provide this feature.
Now, with HTML5 and with the addition of an attribute, it is possible to manage everything without using
any external language.
HTML5 introduces a new attribute to the file input type, multiple, to improve file upload usability. Multiple
is a Boolean attribute that indicates whether the user should be allowed to specify more than one value.
It’s specified inline to the markup input tag:
<input type="file" multiple />
This attribute is supported by the latest versions of Safari, Chrome, Firefox, Internet Explorer, and Opera.
The input control will be rendered according to the browser, with a simple text input with a button on the
side to select the files (e.g., Opera), or with only a button (e.g., Chrome and Safari).
Other browsers, such as Chrome, use the same button label used for a simple file input type. However,
they specify the number of selected files for the user (but not their file names, as Opera and Firefox do).
To carry out a multiple selection, the user will use the SHIFT or CTRL or CMD keys after having clicked on
the Choose Files or Add Files button.
How to build it
From a technical point of view, the only thing you need to be aware of to allow the user to upload multiple
files is to add the multiple attribute in the declaration of the tag file input type.
Here is a complete example:
<!DOCTYPE html>
<html>
<head>
<title>
Solution 4-5: Sending multiple files
</title>
</head>
<body>
<form id="myForm">
<fieldset>
<legend>Solution 4-5: Sending multiple files</legend>
<label>Upload one or more files:</label>
<input type="file" name="multipleFileUpload" multiple />
<br />
</fieldset>
</form>
</body>
</html>
Expert tips
The files that the user selects will have to be sent to the server and processed using server-side language.
Some programming languages, such as PHP, require you to add brackets to the name attribute of the tag
to send multiple files:
<input name="filesUploaded[]" type="file" multiple />
By doing so, PHP will construct an array data type, which will contain the uploaded files on the server. If
you don’t specify the brackets, the programming language will process the files in order and only provide
the last file in your script.
Comments