HTML.form.guide

How to Use HTML5 Input Type 'file' - With Examples

html file upload html input type file html5 input type file html5 input types

If you’re developing a nice website like Facebook or Youtube where subscribers share images and videos, or you’re selling premium content like e-books online, you have to provide a way for users to upload content. In this tutorial, I will show you how to add file uploading capability to your web page like a pro.

The W3C HTML Standard defines several <input > types each designed to handle a specific type of data. For file uploading purposes, the HTML input element, aptly a tag named <input type=“file”>, has been provided. How does it work? Let’s dive straight into the tutorial to find out.

The HTML5 File Input Element

The file element is created using the input type=file as shown below. The first example creates a single file upload box whereas the second example creates a multi-file upload field.

<p>
<label for="profile_pic">Profile Pic: </label>
<input multiple id="profile_pic" name="profile_pic" type="file">
</p>

<p>
<label for="pictures_upload">Pictures: </label>
<input multiple id="pictures_upload" name="pictures[]" type="file">
</p>

Creating a working file upload form involves more than just adding the input element. Read the details below

The Client Side Code

Fire up your favorite text editing program, in my case I will use notepad. Add this code:

<!DOCTYPE html>
<html lang="en">

<head>
	<Title>File Upload Tutorial</Title>
</head>

<body>
	<!--Content will go inside here.-->
</body>

</html>

The line containing <!--Content will go inside here.--> is a comment to make our code easier to read and will not be displayed to the user.

Next, add a form element between the tags.

<form action="uploadfiles.php" method="post" enctype="multipart/form-data">

<!--Content will go inside here.-->

<input type="submit" value="Upload Now">

</form>

The action attribute specifies the script on the server that handles the form submission.

Note:

  • For a form that has file uploads, you have to have the ’enctype’ attribute of the form set to “multipart/form-data”.

  • Similarly, the ‘method’ attribute of the form should be “post” if the form has file uploads.

Add the input element of type ‘file’.

The element must have a ’name’ attribute.

   
<input name="profile_picture" type="file">

There are a few noteworthy properties of the <input type=“file”> element.

By default, the <input type=“file”> element allows only 1 file to be uploaded. If you want to enable the user to upload more than one file, you need to do 2 things:

  • Add a ‘multiple’ attribute to the <input type=“file”> element.
  • Add the opening and closing square brackets on the ’name’ attribute.

Example:

<input multiple name="pictures[]" type="file">

However, for this tutorial, we shall proceed to upload a single file. Save the file with an appropriate name like uploadfiles.php on your web server and keep it open. The file should look like this so far:

<!DOCTYPE html>
<html lang="en">

<head>
	<title>File Upload Tutorial</title>
</head>

<body>
	<!--Content will go inside here.-->
	<form target="uploadfiles.php" method="post" enctype="multipart/form-data">
		<!--Content will go inside here.-->
		<input name="file1" type="file">
		<input type="submit" value="Upload Now">
	</form>
</body>

</html>

This web page completes our work on the client side. Let’s now develop the server-side code.

Handling File Uploads On The Server Side

When the user clicks the “Upload Now” button, the browser will post the form data along with the file contents to the script mentioned in the action attribute (uploadfiles.php) The script then collects the file and saves on the server.

  • Create a folder named “uploads” on your web server at the same path level as the uploadfiles.php file. This is where we will save the uploaded files.
  • Now we have to add the following PHP code to handle the upload. First, we check if the form is posted and then check if the file is uploaded successfully.
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
  if (is_uploaded_file($_FILES['profile_picture']['tmp_name']) ) 
  {

      //save the file

  }
}
  • Now move the uploaded file to the uploads sub-folder using move_uploaded_file() function.


if (move_uploaded_file($_FILES['file1']['tmp_name'], $dest)) 
{
   echo 'File Has Been Uploaded !';
}

The complete PHP script so far (uploadfiles.php)

<html lang="en">
<head>
<Title>File Upload Tutorial</Title>
</head>
<body>
 
	<form action="uploadfiles.php" method="post" enctype="multipart/form-data">
	<p>
	<label for="my_upload">Select the file to upload:</label>
	<input id="my_upload" name="my_upload" type="file">
	</p>
	<input type="submit" value="Upload Now">
	</form>
</body>
</html>
<?php 
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
  if (is_uploaded_file($_FILES['my_upload']['tmp_name'])) 
  { 
  	//First, Validate the file name
  	if(empty($_FILES['my_upload']['name']))
  	{
  		echo " File name is empty! ";
  		exit;
  	}

  	$upload_file_name = $_FILES['my_upload']['name'];
  	//Too long file name?
  	if(strlen ($upload_file_name)>100)
  	{
  		echo " too long file name ";
  		exit;
  	}

  	//replace any non-alpha-numeric cracters in th file name
  	$upload_file_name = preg_replace("/[^A-Za-z0-9 \.\-_]/", '', $upload_file_name);

  	//set a limit to the file upload size
  	if ($_FILES['my_upload']['size'] > 1000000) 
  	{
		echo " too big file ";
  		exit;        
    }

    //Save the file
    $dest=__DIR__.'/uploads/'.$upload_file_name;
    if (move_uploaded_file($_FILES['my_upload']['tmp_name'], $dest)) 
    {
    	echo 'File Has Been Uploaded !';
    }
  }
}

If you upload this php script to your website, you will be able to upload files through the form.

Notes on setting up the web server for successful file uploads

There are several configuration parameters that can affect the file upload. These configuration parameters have to be setup right for the file uploads to work fine.

  1. The folder in which the files are saved should be writable by the script. This is obvious but might be overlooked. The folder must be writable by the script means the web server user (usually www-data ) should have write access to the folder. So setup the folder permissions right. If you have shell access, the folder permissions can be updated using the ‘chmod’ command easily. If you don’t have shell access, or if you have a shared hosting account, updating the folder permissions can be a little tricky. See if your hosting control panel has this feature.

  2. The websever configuration The web server would have a configuration setting that (1) allows/disallows file uploads (2) sets a limit on the size of the file upload. Here are the typical settings you have to check (for PHP)

  • memory_limit
  • upload_max_filesize
  • post_max_size

See Also: