This JavaScript program shows how to upload an image via an AJAX call. The output sequence shows how the page looks at various stages: initially, while selecting the image file, after the image is selected, after the button is pressed and the image is uploaded, and the image file inside the uploads folder.
<!DOCTYPE html> <html> <head> <title>XoaX.net's AJAX Image Uploader</title> </head> <body> <h2>Upload an Image</h2> <form id="idForm" action="ReceiveUpload.php" method="POST"> <input type="file" id="idFile" name="sFile" /><br /><br /> <input type="submit" id="idSubmit" name="sSubmit" value="Upload Image" /> </form> <div id="idResponse" style="margin:5px;"></div> <script type="text/javascript" src="AjaxImageUpload.js"></script> </body> </html>
// Get the HTML elements var qFormElement = document.getElementById('idForm'); var qFileElement = document.getElementById('idFile'); var qResponse = document.getElementById('idResponse'); qFormElement.onsubmit = function(event) { // Stop the form from being submitted event.preventDefault(); // Set the initial message qResponse.innerHTML = 'Uploading...'; // Get the files from the form input; there is only one. var qFile = qFileElement.files[0]; // Make sure that it is an image file if (!qFile.type.match('image.*')) { qResponse.innerHTML = 'This file is not an image.'; return; } // Create a FormData object var qFormData = new FormData(); // Add the file to the AJAX request qFormData.append('sFile', qFile, qFile.name); // Create the HTTP request object var qHttpRequest = new XMLHttpRequest(); // Open the connection qHttpRequest.open('POST', 'ReceiveUpload.php', true); // Handle the completion of the request qHttpRequest.onload = function () { // The request was successful if (qHttpRequest.status == 200) { qResponse.innerHTML = 'Finished!<br />'+qHttpRequest.responseText; } else { qResponse.innerHTML = 'The upload failed.'; } }; // Send the image qHttpRequest.send(qFormData); }
<?php // Display the properties of the file echo "<ul>"; foreach($_FILES['sFile'] as $sKey => $sName) { echo "<li>".$sKey." => ".$sName."</li><br />"; } echo "</ul>"; if(!empty($_FILES['sFile'] ?? null)) { // Get the image file properties. $sFilename = $_FILES['sFile']['name']; $sTempFileName = $_FILES['sFile']['tmp_name']; $sFileExtension = strtolower(pathinfo($sFilename, PATHINFO_EXTENSION)); // Create a path for the uploaded file $sCurrDir = getcwd(); $sUploadFolder = "/uploads/"; $sUploadedFilePath = $sCurrDir.$sUploadFolder.basename($sFilename); if (isset($sFilename)) { // Only accept these file extensiosns. $saValidFileExtensions = ['jpeg','jpg','png','gif']; // Check whether the file extension is valid if (in_array($sFileExtension, $saValidFileExtensions)) { // Print the uploaded file path so that we can verify that it is correct. echo "Uploaded File Path: <b>".$sUploadedFilePath."</b><br /><br />"; // Move the file out of the temp directory to the desired location. $bSuccessfulUpload = move_uploaded_file($sTempFileName, $sUploadedFilePath); if ($bSuccessfulUpload) { echo "The image <b>".basename($sFilename)."</b> has been uploaded!<br /><br />"; // Display a small version of the image echo '<img src=".'.$sUploadFolder.basename($sFilename).'" width="400" />'; } else { echo "The image file move failed!"; } } else { echo "Error: only JPEG, JPG, PNG and GIF images are supported!"; } } } ?>
© 20072024 XoaX.net LLC. All rights reserved.