An image's dimensions must be verified before assessing its criteria

In my project, I am facing a challenge with image uploading functionality. The requirement is to check if the uploaded image exceeds the maximum criteria set. If it does, an alert message should be displayed.

alert("Height exceeds our maximum criteria. Please select an image within height and width limits etc.");

Although I have successfully implemented all functionalities, I encounter an issue when uploading images. I need to display the actual height and width of the selected image, but instead, I receive the dimensions of the previously selected image.

Below is a snippet of my code:

<!DOCTYPE html>
<html>
<head>
<link href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet"></link>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

    function readImage(file) {
        var reader = new FileReader();
        var image = new Image();
        var maxh = 800;
        var maxw = 800;
        //rest of the code
    }

$("#choose").change(function (e) {
    //file upload logic
});

</script>

<style>
#uploadPreview img {
    height:32px;
}
</style>
</head>
<body >
<input type="file" id="choose" multiple="multiple" />
<br>
<div id="uploadPreview"></div>
</body>
</html>

Issue: I consistently retrieve the dimensions of the previously selected image, not the current one. This leads to inaccurate information being displayed.

I hope my question is clear. Thank you for your assistance.

Answer №1

Take a look at THIS FIDDLE. The key point here is that your current logic is incorrect - you're comparing the height and width to the dimensions of the previously uploaded image (blah), when in reality, you need to first upload the image to obtain its properties and then decide on the next steps.

Refer to the example below which is based on this specific answer on SO, tailored for your needs.

HTML

<input type="file" id="choose" multiple="multiple" />
<br>
<div id="uploadPreview"></div>

JS

function readImage(file) {

    var reader = new FileReader();
    var image = new Image();
    var maxh = 800;
    var maxw = 800;
    reader.readAsDataURL(file);
    reader.onload = function (_file) {
        image.src = _file.target.result; // url.createObjectURL(file);
        image.onload = function () {
            var w = this.width,
                h = this.height,
                t = file.type, // ext only: // file.type.split('/')[1],
                n = file.name,
                s = ~~(file.size / 1024) + 'KB';
            if (w > maxw && h > maxh) {
                alert("Height exceeds maximum criteria, please select an image with a maximum height and width of 2024x2024");
                alert(width);
                alert(height);
            } else {
                $('#uploadPreview').html('<img src="' + this.src + '"> ' + w + 'x' + h + ' ' + s + ' ' + t + ' ' + n + '<br>');
            }

        };
        image.onerror = function () {
            alert('Invalid file type: ' + file.type);
        };
    };

}
$("#choose").change(function (e) {
    if (this.disabled) return alert('File upload not supported!');
    var F = this.files;
    if (F && F[0]) for (var i = 0; i < F.length; i++) readImage(F[i]);
});

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

Tips on importing anime js after it has been successfully installed through npm

Today, I added anime js as a dependency to my package.json file. The version 3.0.1 is visible in the dependencies list. I used npm to install it. Next step was creating a folder and a JavaScript file in the public directory. I set up a simple event liste ...

Play framework fails to apply style attributes correctly

When working with play-framework 2.3.x, I am in the process of creating a form and would like to show/hide it based on a model attribute. Typically, setting the style attribute manually using style = "display: none" and style = "display: block" works fine. ...

In JavaScript using Vue.js, you can compare various objects within an array and calculate the total sum of their values based on a shared

This task may pose a challenge for those new to programming, but seasoned developers should find it relatively simple. I've been searching for a solution without success so far, hence turning to this platform for help. Here's the scenario at han ...

JavaScript's speciality - altering the Jquery fade in and fade out effect on Firefox browsers

Utilizing Jquery, I implemented a feature on a table where moving the mouse over a row changes its color. The Javascript code was specifically designed for IE7 and works flawlessly there. However, when tested in Firefox, the text fades along with the backg ...

Using AJAX and PHP to retrieve and store variables in a database

This is my first time attempting this and I'm feeling frustrated because I'm struggling to figure out how everything fits together. I have a function that needs to call two PHP files - one for selecting information from a database, and the other ...

Passing parameters to $http.get in Angular can be achieved by including them

I am attempting to send a params object to the $http.get() method. My params are structured as follows: var params = { one: value, two: value } I am trying to pass them into my function like this: $http.get('/someUrl', params) .success(fun ...

Difficulty arises when attempting to create JSON using the Array.push() function from the data received via Ajax. The generated JSON is not successfully populating the tbody element

I am facing an issue while populating my tbody with data using the code below: function adaptSelectedBanks(banks) { console.log(banks.length); $(function() { banks.forEach(function (ba) { var c ...

Discover how to effortlessly unveil JSON data by clicking on data retrieved from an API

After successfully parsing data from a Tumblr API, I encountered an issue when introducing tags within the body description, which includes images and hyperlinks. The main task at hand is to create a list of blog titles where the corresponding blog descri ...

What is the best way to output neat and tidy JavaScript code from a custom view helper in Rails

As I was working on my update.js.erb file using Rails 3, I realized that I was repeating a lot of code. To simplify things, I attempted to move it all into a helper function. However, I encountered an issue where the helper was not producing clean JavaScri ...

Utilizing Pseudo Elements within the QT Designer Interface

I was attempting to add a vertical line to the left of a button with a hover effect using a pseudo-element in qt-designer styleSheet, but it was not displaying correctly. Here is the code I used: QPushButton{ position: relative; padding: 10px 20px; border: ...

JavaScript not functioning properly for the Sibice challenge on Kattis

Currently, I am in the process of learning JavaScript and a friend recommended trying out Kattis for solving tasks, even though it might not be ideal for JS. As part of this challenge called Sibice, the goal is to determine if matches will fit into a box. ...

What could be improved in this AngularJS code snippet?

Currently, I am immersed in an AngularJS book and have extracted the following code snippet directly from its pages: <!DOCTYPE html> <html ng-app='myApp'> <head> <title>Your Shopping Cart</title> </head> & ...

Developing a personalized camera feature using ReactJS

After searching for a suitable npm library to create a custom camera component within my ReactJS project, I came across an article providing detailed information at this link. However, I am facing challenges in converting the existing pure JavaScript code ...

Unable to add an event while looping through a NodeList in JavaScript

Seeking assistance in iterating a NodeList object using javascript, and implementing a click event for each item : document.addEventListener("DOMContentLoaded", async () => { try { posts.map(post => { container.innerHTML += out ...

Having trouble getting the jQuery keydown trigger to function properly?

After the document has finished loading, I execute this script: $(function () { $("input").keydown(); }); This script is part of a chrome extension that runs on every page the user visits. However, it does not work on certain websites like Twitter ...

Animate all shapes in SVG to rotate around a central pivot point

I am looking for a simple way to make an SVG graphic rotate around its center point. The rotation doesn't need to be smooth, just a 90 degree turn and back every second. https://i.sstatic.net/H6CTF.png Here is the SVG code: <?xml version="1.0" e ...

Storing information into Database with AJAX

I have a webpage with a form, and I'm trying to save data into my database using Ajax upon form submission. However, I keep encountering an error POST 500 (Internal Server Error) Am I missing something here? Can someone please guide me in the ...

Fetch a list of 10 items at a time using AngularJS with Ionic framework's infinite scroll feature

I'm currently working on incorporating an ion-infinite-scroll feature using the ionic framework. My REST API allows me to set the index in order to request a specific range of data. Here's what my Service looks like, with 'begin' and &a ...

Issue with Bootstrap: Navbar elements shifting when page width is decreased

I am facing an issue with my two navbars, one above the other. The top bar is thinner and consists of two navigation items aligned to the right of the page. Despite setting it not to collapse when the page width is reduced, the items suddenly disappear whe ...

Using NodeJS: Import the file, run it, then delete all traces

I am facing an issue. Within my primary program, I have multiple functions in operation. At a certain point, I trigger a random script (file_XXX.js) which can vary (multiple different files). This particular file is executed and then the main program cal ...