Ajax File Upload
A file upload field is a form field where the user can specify a file to include when the form is submitted.
Optionally, the file upload field can specify the type of file to accept. That and other features are mentioned at the input type="file" Mozilla developer web page.
Here is what a file upload form field looks like (not a live example).
The style of the file upload form field is provided by the browser. CSS has little effect on it.
Ajax can be used to upload a file as soon as it is specified in the upload form field. This article describes how. There is no delay waiting for the person to tap a submit button.
Here is what happens.
-
Someone uses the form upload field.
-
Immediately, the browser proceeds to send the file to a PHP script on the server.
-
When the file has been uploaded and saved on the server, a "Success" message is displayed to the user.
Three things are required.
-
A file upload form field.
-
The JavaScript to immediately upload the file.
-
The PHP script to save the file to your server.
The first two items, the upload field and the JavaScript, are both on the same web page. The last item, the PHP script, is separate and will be located on your server.
Here is a testing web page with the upload field and JavaScript that you may use. It requires one customization.
<!DOCTYPE html> <html> <head> <title>Ajax File Upload</title> </head> <body> <div style="display:table; margin:.5in auto;"> <h1>Ajax File Upload</h1> <input type="file" onchange="uploadFile(this)"> <script type="text/javascript"> function uploadFile(d) { var url = "/uploadtest/FileUploadHandler.php"; var http = new XMLHttpRequest();; if(! http) { alert("Sorry, unable to connect to the internet."); return; } var formData = new FormData(); formData.append("file", d.files[0]); http.onreadystatechange = function() { if(http.readyState == 4 && http.status == 200) { alert(http.responseText); } else { alert('Upload error, status code: '+http.status+' '+http.statusText); } } http.open("POST",url,true); http.send( formData ); } </script> </div> </body> </html>
In the above source code, you'll see the file upload field is colored green and all of the JavaScript colored blue — except the part that needs to be customized.
The part that needs to be customized is a few lines down from the top of the JavaScript. It is colored red:
var url = "/uploadtest/FileUploadHandler.php";
That red part, /uploadtest/FileUploadHandler.php
, is where you specify the location of the PHP script.
Here is the source code of the PHP script.
<?php
$imageLocation = $_SERVER['DOCUMENT_ROOT'].'/uploadtest/uploadimages';
if( isset($_FILES['file']['error']) and (!$_FILES['file']['error']) and $_FILES['file']['size']>0 )
{
if(move_uploaded_file($_FILES['file']['tmp_name'],$imageLocation.= '/'.$_FILES['file']['name'])) { echo 'Success'; }
else { echo 'Error'; }
}
else { echo 'No File Received'; }
?>
At the top of the PHP code is where you specify the location to save the uploaded files. The location would be a directory relative to the document root (the directory where your domain's home or index web page file is located).
$imageLocation = $_SERVER['DOCUMENT_ROOT'].'/uploadtest/uploadimages';
Replace the red part, /uploadtest/uploadimages
, with the location of the directory for uploaded files.
Upload the PHP script with file name FileUploadHandler.php
(or other *.php
file name) and make a note of its location. Update the JavaScript with the PHP script's location.
The PHP script is now installed.
Upload the web page to your server. It can be anywhere that a browser can reach. Load the web page into your browser.
Use the form.
You should get a "Success" message back. If the message is "Fail" the script was unable to save the file. If you get a "No File Received" message, it means either no file arrived at the PHP script or the file was empty.
When you get the "Success" message, the file should have been stored on your server. It will have the same file name as uploaded. (You may need to reload your FTP listing so the uploaded file name is visible.)
You now have the basic functionality of an immediate-upload file upload form field.
The code may be modified for additional features. Examples are receiving an email when a file is uploaded, constructing the URL of the newly uploaded file, or preventing previously uploaded files from being overwritten when another file of the same name is uploaded.
(This content first appeared in Possibilities newsletter.)
Will Bontrager