Verifying conditions in an AJAX-based upload system using JavaScript

Recently, I was working on implementing a JavaScript/AJAX upload system with a progress indicator based on a tutorial. The process went smoothly, and I even managed to include a CSS progress bar for visual representation. However, I encountered a hurdle that I'm struggling to overcome - adding conditions such as file type, size, and whether the file is set or not. Below is a snippet of my code (upload.php):

<?php
foreach($_FILES['file']['name'] as $key => $name){
        if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
            $uploaded[] = $name;
        }
    }
    if(!empty($_POST['ajax'])){
        die(json_encode($uploaded));
    }
?>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="upload.js"></script>
</head>
<body>
        <div id="uploaded">
            <?php

            if (!empty($uploaded)){
                foreach ($uploaded as $name){
                    echo '<div><a href="files/',$name,'">',$name,'</a></div>';
                }
            }

            ?>
             </div>
<div id="upload_progress"></div>
        <div>
            <form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" />
<input type="submit" id="submit" value="upload" />
</form>

Furthermore, here is the JavaScript file (upload.js) associated with this project:

var handleUpload = function(event){
    event.preventDefault();
    event.stopPropagation();

    var fileInput = document.getElementById('file');

    var data = new FormData();

    data.append('ajax', true);
    for (var i = 0; i < fileInput.files.length; ++i){
        data.append('file[]', fileInput.files[i]);
    }   

    var request = new XMLHttpRequest();

    request.upload.addEventListener('progress', function(event){
        if(event.lengthComputable){
            var percent = event.loaded / event.total;
            var progress = document.getElementById('upload_progress');

            while (progress.hasChildNodes()){
                progress.removeChild(progress.firstChild);
            }
            progress.appendChild(document.createTextNode(Math.round(percent * 100) +' %'));
            document.getElementById("loading-progress-17").style.width= Math.round(percent * 100) +'%';
        }
    });
    request.upload.addEventListener('load', function(event){
        document.getElementById('upload_progress').style.display = 'none';
    });
    request.upload.addEventListener('error', function(event){
        alert('Upload failed');
    });
    request.addEventListener('readystatechange', function(event){
        if (this.readyState == 4){
            if(this.status == 200){
                var links = document.getElementById('uploaded');
                var uploaded = eval(this.response);
                var div, a;
                for (var i = 0; i < uploaded.length; ++i){
                    div = document.createElement('div');
                    a = document.createElement('a');
                    a.setAttribute('href', 'files/' + uploaded[i]);
                    a.appendChild(document.createTextNode(uploaded[i]));
                    div.appendChild(a);
                    links.appendChild(div);
                }
            }else{
                console.log('server replied with HTTP status ' + this.status);
            }
        }
    });
    request.open('POST', 'upload.php');
    request.setRequestHeader('Cache-Control', 'no-cache');
    document.getElementById('upload_progress').style.display = 'block';
    request.send(data);

}

window.addEventListener('load', function(event){

    var submit = document.getElementById('submit');
    submit.addEventListener('click', handleUpload);
});

I am in search of guidance regarding how I can incorporate a condition to check if the file size is under 50MB within this upload system. Any assistance in this matter would be greatly appreciated. Thank you.

Answer №1

To easily check for specific criteria such as file size, you can incorporate it into your code like this:

Examine these lines within your code:

for (let i = 0; i < input.files.length; ++i){
    data.append('file[]', input.files[i]);
}

This section is where files are included in FormData before sending them to the server. You can introduce conditions here, such as a size restriction:

for (let i = 0; i < input.files.length; ++i){
    // The file's size is measured in bytes
    if(input.files[i].size <= MAX_FILESIZE_IN_BYTES){
        data.append('file[]', input.files[i]);
    }
}

I trust this explanation proves useful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Toggling the form's value to true upon displaying the popup

I have developed an HTML page that handles the creation of new users on my website. Once a user is successfully created, I want to display a pop-up message confirming their creation. Although everything works fine, I had to add the attribute "onsubmit= re ...

"Implementing a column template in jqgrid post-creation: A step-by-step

Can't apply column template with Free jqgrid once it's been created. I've attempted: var newOrderPriceTemplate = { align: "center", formatter: "showlink", formatoptions: { onClick: function() { alert('clicked&apos ...

Tips on inserting an image within a div that is created dynamically

I'm currently working on creating dynamic div elements in my JavaScript using the code below: var div = $('<div id="a1"></div>').html("<font color=green>This is a demo</font>"); I am struggling to figure out how to ...

Is Microsoft currently developing or backing any solutions that can enhance the scalability of AJAX Comet technology?

There seems to be a lot of discussion surrounding ajax comet in various questions and articles. I came across some information suggesting that it may not be very scalable with ASP.Net, but there are links available to enhance its scalability. I am curious ...

Is it possible to make this functionality Angular-friendly?

I am in the process of transforming a Bootstrap + jQuery theme into Angular JS, and I am encountering some challenges along the way. One issue is related to the functionality provided in the JS file of the theme: /* Sidebar Navigation functionality */ var ...

Vuejs: Limiting the number of items in an li tag to 5

selectPreviousSearch(index) { this.search = this.searchHistory[index]; this.showSearchHistory = false; }, <input class="form-control bg-light-blue" id="SearchText" type="text" v-model="search" @keydown.enter = 'ent ...

Unleash the Power of Your Webpage: Instantly Engage Full

Is there a way to automatically make a webpage open in full screen mode as soon as it is loaded? Here's what I currently have: var elem = document.documentElement; function openFullscreen() { if (elem.requestFullscreen) { elem.requestFull ...

Send an API call for every item in a given list

There is a function that I am working with: updateCustomers = (input) => { //let urls = input; let urls = [{ name: "localhost:8081", url: "http://localhost:8081" }, { name: "localhost:8082", url: "http://localhost:8081" }, { ...

Develop and share a function to be assessed within a different scope's context in JavaScript

Currently, I'm exploring the use of angular and bootstrap tour and I have a challenge in trying to isolate objects within their own area without storing them in the controller. My goal is to store an object in the service, which also contains function ...

Canvas Frustratingly Covers Headline

Several months ago, I successfully created my portfolio. However, upon revisiting the code after six months, I encountered issues with its functionality. Previously, text would display above a canvas using scrollmagic.js, and while the inspector shows that ...

Storing dataset characteristics in a JSON file utilizing Vue.js form response

I am currently working on creating a JSON file to store all the answers obtained from a Form. Some of the input fields have an additional dataset attribute (data-tag). When saving the Form, I aim to extract these 'tags' and include them in the JS ...

Is there a way to transform the SmartyStreets' jQuery.LiveAddress plugin into its JavaScript SDK?

My website currently utilizes the jQuery.LiveAddress plugin, however, it was deprecated and subsequently removed by SmartyStreets back in 2014. <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <s ...

Displaying a div after a successful form submission using Jquery

I created two popup windows. One is used to ask the user whether they want to submit the form, and if they click 'yes', the form is submitted. The issue I encountered is that the other popup window should be shown after the form is successfully s ...

Ways to access information received from AngularJS in a different Javascript file

I am currently using Angular to retrieve output from a controller and display it using ng-bind. However, I have another separate JavaScript file that needs to utilize a value returned from Angular. In the example code provided below, the TestAppCtrl is ca ...

When using VueJS routing with the same component, the OWL Carousel does not get triggered

Hello I am currently experiencing an issue with VueJS rendering images into a Carousel plugin (OwlCarousel) when loading the same component with different variables. When initially loading the page with images, everything functions correctly and the caro ...

Exploring numerical elements in interactive content

Struggling with the Wikipedia API and encountering issues with the results that are returned. {"query":{ "pages":{ "48636":{ "pageid":48636, Concerned about how to access a specific ID (such as 48636) without knowing it in advance ...

Steps for displaying the output of a post request in printing

I am currently working on creating a basic search bar functionality for daycares based on user input. I am utilizing a post request to an API and receiving back a list of daycares that match the input. Below is the code snippet: <template> <div ...

submitting two contact forms using ajax

Looking to enhance my knowledge of form design... Hello there! I'm currently working with two contact forms on the same page, both utilizing ajax for submissions. Each form functions properly when standalone, but as soon as I integrate them togethe ...

Can a variable containing HTML code be iterated through with a loop?

I am currently working on setting up a select button that will receive options from an ajax call. The ajax call is functioning properly. However, I am facing a challenge when trying to create a variable containing the HTML. I am unsure of how to iterate a ...

Utilizing onMouseEnter and onMouseLeave events in React using hooks

My goal is to create a drop-down menu with a delay, allowing users to hover over the child list items before they disappear. However, I seem to have made an error somewhere but can't pinpoint it. It's likely just a simple mistake that my eyes are ...