The element input with the type = “file” attribute is responsible for selecting files on the form:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>File Upload in HTML5</title> </head> <body> <form enctype="multipart/form-data" method="post" action="#"> <div class="form-group" style="margin-bottom: 15px;"> <input type="file" name="file" /> </div> <div class="form-group" style="margin-bottom: 15px;"> <input type="submit" value="Submit" /> </div> </form> </body> </html>
When you click on the “Select File” button, a dialog box for selecting a file opens. And after selection, the name of the selected file is displayed next to the button.
It is important to note that in order to submit a file to the server, the form must have an attribute enctype=”multipart/form-data”.
With the help of a number of attributes, we can further customize the file selection elements:
- accept : sets the file type that are valid for selection
- multiple : allows you to select multiple files
- required : requires mandatory installation of the file
For example, multiple choice of files:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>File Upload in HTML5</title> </head> <body> <form enctype="multipart/form-data" method="post" action="#"> <div class="form-group" style="margin-bottom: 15px;"> <input type="file" name="file" multiple /> </div> <div class="form-group" style="margin-bottom: 15px;"> <input type="submit" value="Submit" /> </div> </form> </body> </html>
When you click on the button, a dialog box for selecting files also opens, only now, holding down the CTRL or Shift key, we can select several files, and after selection, the number of selected files will be displayed next to the button: