Problem solve Get help with specific problems with your technologies, process and projects.

The Ajax file upload example with pure JavaScript

There was a time when the ability to upload files through the browser was a daunting challenge. Not only did a server-side component need to exist that could handle the incoming stream of data, but the client side facilities were poor as well.

Fortunately, HTML5 file input form tags have greatly simplified things on the client side, but when it comes to the creation of Ajax and JavaScript file uploading functionality, many developers turn to popular libraries such as jQuery or the Dojo Toolkit to accomplish the task, bringing needless complexity to their applications.

The easiest and simplest way to upload a file with Ajax is to use pure JavaScript and leave the bulky libraries and frameworks behind.

Ajax file uploads

The following steps describe how to perform an Ajax based JavaScript file upload to a server:

  1. An HTML5 input form element must be included in the webpage that renders in the client’s browser
  2. A JavaScript method must be coded to initiate the asynchronous Ajax based file upload
  3. A component must exist on the server to handle the file upload and save the resource locally
  4. The server must send a response to the browser indicating the JavaScript file upload was successful
  5. The client’s browser provides an Ajax based response indicating the file uploaded successfully

In this example, the JavaScript file upload target is an Apache Web Server, so the server-side component that handles the Ajax request will be written in PHP. If a Tomcat or Jetty server was the upload target, a Java based uploader could be coded on the server-side.

Website Performance Tips and Tricks

Is website performance a problem? It doesn’t have to be. Here’s how to fix it:

Web performance doesn’t have to be a problem.

HTML5 file tags

HTML5 introduced a new type of input form field named file. When a browser encounters this tag, it renders a fully functional file picker on the web page. Together with an HTML5 button tag that can trigger a JavaScript method, these two elements represent the required markup elements needed to begin the Ajax and JavaScript file upload process.

The following HTML5 tags provide the components required to add a file selector and an upload button to any web page:

<input id="fileupload" type="file" name="fileupload" />
<button id="upload-button" onclick="uploadFile()"> Upload </button>

The button kicks off a method named uploadFile() which contains the JavaScript file upload logic.

<script>
async function uploadFile() {
    let formData = new FormData();           
    formData.append("file", fileupload.files[0]);
    await fetch('/upload.php', {
      method: "POST", 
      body: formData
    });    
    alert('The file has been uploaded successfully.');
}
</script>

JavaScript file upload logic

The above script tag contains nothing but pure JavaScript. There is no jQuery or Dojo thrown into the mix. And the logic is fairly straight forward:

  • Create a FormData object to contain the information to be sent to the server
  • Add the chosen file to be uploaded to the FormData object
  • Asynchronously call server-side resource to handle the upload
    • The server-side resource is invoked through the POST method
    • The server-side resource is passed the FormData which contains the file
    • In this example that server-side resource is named upload.php
  • When notified that the JavaScript file upload was successful, send an Ajax based alert to the client

All of the HTML and JavaScript logic will be contained in a single file named uploader.html. The complete HTML looks as follows:

<!DOCTYPE html> 
<html> 
 <head> 
  <title> Ajax JavaScript File Upload Example </title> 
 </head> 
 <body>
  <!-- HTML5 Input Form Elements -->
  <input id="fileupload" type="file" name="fileupload" /> 
  <button id="upload-button" onclick="uploadFile()"> Upload </button>

  <!-- Ajax JavaScript File Upload Logic -->
  <script>
  async function uploadFile() {
  let formData = new FormData(); 
  formData.append("file", fileupload.files[0]);
  await fetch('/upload.php', {
    method: "POST", 
    body: formData
  }); 
  alert('The file has been uploaded successfully.');
  }
  </script>

 </body> 
</html>

Apache file upload processing

JavaScript file upload

Required JavaScript file upload components.

When an asynchronous JavaScript file upload happens, a server-side component must exist to handle the incoming file and store it. Since this example uses an Apache HTTP Server (AHS), and since PHP is the lingua franca of AHS, a file named upload.php that contains a small PHP script to save the incoming file to a folder named uploads is required:

<?php

/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];

/* Choose where to save the uploaded file */
$location = "upload/".$filename;

/* Save the uploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) { 
  echo 'Success'; 
} else { 
  echo 'Failure'; 
}

?>

The PHP script is fairly straight forward. It obtains the name of the file being uploaded, and then creates a spot in a folder named upload to save the file. PHP’s move_uploaded_file method is then used to save the uploaded file to this new location.

Run the JavaScript file upload example

The files used in this example, along with a folder named upload, must be added to the htdocs folder of AHS. When a client accesses the uploader.html file through a browser, the client will be able to upload a file to the server using Ajax and pure JavaScript.

Ajax file upload example

A pure JavaScript file uploader simplifies Ajax based interactions with the server.

 

 

 

 

 

 

 

 

 

 

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

SearchAppArchitecture

SearchSoftwareQuality

SearchCloudComputing

SearchSecurity

SearchAWS

Close