AJAX Image Upload

Core JavaScript

AJAX Image Upload

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.

AjaxImageUpload.html

<!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>

AjaxImageUpload.js

 
var qFormElement = document.getElementById('idForm');
var qFileElement = document.getElementById('idFile');
var qResponse = document.getElementById('idResponse');

qFormElement.onsubmit = function(event) {
	 
    event.preventDefault();
     
    qResponse.innerHTML = 'Uploading...';

     
    var qFile = qFileElement.files[0];
     
    if (!qFile.type.match('image.*')) {
        qResponse.innerHTML = 'This file is not an image.';
        return;
    }

     
    var qFormData = new FormData();
     
    qFormData.append('sFile', qFile, qFile.name);

     
    var qHttpRequest = new XMLHttpRequest();
     
    qHttpRequest.open('POST', 'ReceiveUpload.php', true);
     
    qHttpRequest.onload = function () {
       
      if (qHttpRequest.status == 200) {
        qResponse.innerHTML = 'Finished!<br />'+qHttpRequest.responseText;
      } else {
        qResponse.innerHTML = 'The upload failed.';
      }
    };
     
    qHttpRequest.send(qFormData);
}

ReceiveUpload.php

<?php

     
    echo "<ul>";
    foreach(&dollar;_FILES['sFile'] as &dollar;sKey => &dollar;sName) {
       echo "<li>".&dollar;sKey." => ".&dollar;sName."</li><br />";
    }
    echo "</ul>";

   if(!empty(&dollar;_FILES['sFile'] ?? null)) {
         
        &dollar;sFilename = &dollar;_FILES['sFile']['name'];
        &dollar;sTempFileName  = &dollar;_FILES['sFile']['tmp_name'];
        &dollar;sFileExtension = strtolower(pathinfo(&dollar;sFilename, PATHINFO_EXTENSION));

         
        &dollar;sCurrDir = getcwd();
        &dollar;sUploadFolder = "/uploads/";
        &dollar;sUploadedFilePath = &dollar;sCurrDir.&dollar;sUploadFolder.basename(&dollar;sFilename);

        if (isset(&dollar;sFilename)) {

             
            &dollar;saValidFileExtensions = ['jpeg','jpg','png','gif'];

             
            if (in_array(&dollar;sFileExtension, &dollar;saValidFileExtensions)) {

                 
                echo "Uploaded File Path: <b>".&dollar;sUploadedFilePath."</b><br /><br />";

                 
                &dollar;bSuccessfulUpload = move_uploaded_file(&dollar;sTempFileName, &dollar;sUploadedFilePath);

                if (&dollar;bSuccessfulUpload) {
                    echo "The image <b>".basename(&dollar;sFilename)."</b> has been uploaded!<br /><br />";
                     
                    echo '<img src=".'.&dollar;sUploadFolder.basename(&dollar;sFilename).'" width="400" />';
                } else {
                    echo "The image file move failed!";
                }
            } else {
                echo "Error: only JPEG, JPG, PNG and GIF images are supported!";
            }
        }
    }
?>

 

Initial

 

 

Select a File

 

 

File Selected

 

 

Uploaded Image

 

 

Upload Folder

 

 

Xổ số miền Bắc