JQuery Multiple File Upload and Remove

jQuery

File Upload Event

$("#upload-vehicle-variant-image-modal").on('change', 'input[name="file"]', function(e) {
    // Event handler for file input change in the modal
    for (let i = 0; i < e.target.files.length; i++) {
        let myFile = e.target.files[i];
        let myFileID = "FID" + (1000 + Math.random() * 9000).toFixed(0);

        // Store file details in the filesToUpload array
        filesToUpload.push({
            file: myFile,
            size: myFile.size,
            FID: myFileID,
            name: myFile.name
        });
    }
    // Update the display after file upload
    display();
    // Reset the input to null - addressing a Chrome bug
    e.target.value = null;
});

This code uses jQuery to attach an event handler to the change event of the file input with the name “file” within the element with the ID “upload-vehicle-variant-image-modal.” When users select files using the file input, the event handler captures each file’s details (name, size, and a generated ID) and adds them to the filesToUpload array. After updating the array, the display function is called to update the UI.

File Removal Event

$(document).on('click', '.remove-button', function() {
    // Event handler for the removal of files
    var fidToRemove = $(this).data('fid');
    for (let i = 0; i < filesToUpload.length; i++) {
        // Remove the file with the specified FID from the filesToUpload array
        if (filesToUpload[i].FID === fidToRemove) {
            filesToUpload.splice(i, 1);
            break;
        }
    }
    // Update the display after file removal
    display();
});

This code uses event delegation to handle the click event for elements with the class “remove-button.” When a user clicks on the remove button associated with a file, it retrieves the file’s FID (File ID) from the button’s data attribute and removes the corresponding file from the filesToUpload array. After removal, the display function is called to update the UI.

Display Function

const display = () => {
    // Function to update the display of uploaded files
    $('#file-list').empty();
    for (let i = 0; i < filesToUpload.length; i++) {
        // Append each file's details to the file list
        $("#file-list").append(`<li class="list-group-item d-flex justify-content-between align-items-center my-2 border">
          <div>${filesToUpload[i].name} - ${bytesToMB(filesToUpload[i].size)} MB</div>
          <div><a class="remove-button" data-fid="${filesToUpload[i].FID}"><i class="fa fa-close"></i></a></div>
          <div class="image-parent">
              <img src="${URL.createObjectURL(filesToUpload[i].file)}" class="img-fluid" alt="quixote">
          </div>
        </li>`);
    }
    // Update the file upload count
    $("#upload-vehicle-variant-image-modal .fileuploadCount").val(`Total file upload: ` + filesToUpload.length);
};

This function updates the display of uploaded files. It empties the existing file list, iterates through the filesToUpload array, and appends each file's details to the file list. The details include the file name, size, a remove button, and a thumbnail preview. The file upload count is also updated. The bytesToMB function is assumed to be defined elsewhere and converts file sizes to megabytes.

Final Code

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
  </head>
  <body>
  <input type="file" name="file" multiple>
<ul class="list-group rounded-0" id="file-list"></ul>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
 <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<script>
   var filesToUpload = []; // Array to store files
    $('input[name="file"]').on('change', function(e) {
        for (let i = 0; i < e.target.files.length; i++) {
            let myFile = e.target.files[i];
            let myFileID = "FID" + (1000 + Math.random() * 9000).toFixed(0);

            filesToUpload.push({
                file: myFile,
                size: myFile.size,
                FID: myFileID,
                name: myFile.name
            });
        }
        display();
        // Reset the input to null - nice little Chrome bug!
         e.target.value = null;
    });

    $(document).on('click', '.remove-button', function() {
        var fidToRemove = $(this).data('fid');
        for (let i = 0; i < filesToUpload.length; i++) {
            if (filesToUpload[i].FID === fidToRemove) {
                filesToUpload.splice(i, 1);
                break;
            }
        }
        display();
    });
// HTML element to display the file list
    const display = () => {
        $('#file-list').empty();
        for (let i = 0; i < filesToUpload.length; i++) {
        $("#file-list").append(`<li class="list-group-item d-flex  justify-content-between align-items-center my-2 border">
          <div>${filesToUpload[i].name}- ${bytesToMB(filesToUpload[i].size)}-MB</div>
          <div><a class="remove-button" data-fid="${filesToUpload[i].FID}"><i class="fa fa-close"></i>Remove</a></div>
          <div class="image-parent">
              <img src="${URL.createObjectURL(filesToUpload[i].file)}" class="img-fluid" alt="quixote">
          </div>
        </li>`);
        }
        $("#upload-vehicle-variant-image-modal .fileuploadCount").val(`Total file upload: `+filesToUpload.length)
    };


    $("#upload-vehicle-variant-image-modal").on('click','.UploadImageBtn', function(){
        let formData = new FormData();

        for (let i = 0; i < filesToUpload.length; i++) {
        formData.append("files", filesToUpload[i].file);
        }

        console.log('formData:::::', formData)

        $.ajax({
                type: "POST",
                url: "/admin/fleet/vehicle-variant-upload-image",
                data: formData,
                processData: false, 
                contentType: false,
                success: function(data){
                    console.log('RESPONSE', data)
                    if(data.statusCode == "200"){
                        createToast({
                    title: "ALERT",
                    msg: data.message,
                    type: "positive"
                    });
                   setTimeout(function(){
                    location.reload()
                   },500)
                    }else{
                        createToast({
                            title: "ALERT",
                            msg: data.message,
                            type: "negative"
                        });
                    }
                },
                error:function(error){
                    console.log('ERORR:::::::', error)
                },
                dataType: 'JSON'
            });

    })



function bytesToMB(bytes) {
    return (bytes / (1024 * 1024)).toFixed(2);
}
</script>
  </body>
</html>