Avoid allowing image uploads that are too large in size

Is there a way to block an image from being uploaded if it exceeds a specified size limit? Currently, I am using angular-base64-upload and although my error message appears when the image is too large, the image still gets uploaded. I'm puzzled as to why the image is still able to upload even when it surpasses the set limit. Any thoughts on this issue would be greatly appreciated. Thank you.

HTML

<div ng-controller="UpLoadImage">

<div ng-repeat="step in stepsModel">
    <img class="thumb" ng-src="{{step}}"/>
</div>

<label for="file">Add Creative</label>

<form name="form">
    <input type='file' ng-model='files' name='files' multiple accept='image/*, .zip' maxsize='50' onload='onLoad'
           ng-model-instant onchange='angular.element(this).scope().imageUpload(this)' required
           base-sixty-four-input>
    <span ng-show='form.files.$error.maxsize'>Files must not exceed 50 KB</span>
</form>

App.js

angular.module('myApp', ['naif.base64'])
.controller('UpLoadImage', function ($scope, $http, $window, $rootScope) {

    $scope.imageUpload = function (element) {
        var reader = new FileReader();
        reader.onload = $scope.imageIsLoaded;
        reader.readAsDataURL(element.files[0]);
    };

    $scope.imageIsLoaded = function (e) {
        $scope.$apply(function () {
            $scope.stepsModel.push(e.target.result);
        });

        $scope.onLoad = function (e, reader, file, fileList, fileOjects, fileObj) {
            alert('image uploaded');
        };
    };

    $scope.stepsModel = [];
})

Answer â„–1

Within your code, the input is actively waiting for an onchange event to trigger the upload process - there is no restriction on this event being executed.

By utilizing form.files.$error.maxsize, you can determine whether the change event should proceed with attempting the upload by checking if it returns a boolean value of true or false.

A recommendation is to relocate your upload functionality into the controller for better organization.

If you opt to use ng-change, you can simplify referencing your controller method by employing:

ng-change="imageUpload(this, form.files.$error.maxsize)"

Expanding the imageUpload function to accept an additional argument allows you to assess if the image size exceeds the limit before proceeding:

$scope.imageUpload = function (element, maxSizeError) {

    if(maxSizeError) { 
        // handle error logic
     } else {
        var reader = new FileReader();
        reader.onload = $scope.imageIsLoaded;
        reader.readAsDataURL(element.files[0]);
     }
};

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

Facing continuous 404 errors while working with nodejs and express

While attempting to collect data from a local host webpage's registration form that captures user information, I encounter an issue upon pressing the submit button A 404 Error is displayed stating "page not found", preventing the collection and out ...

Looking for guidance and bug assistance in HTML and JS, possibly involving PHP and MySQL. Can anyone offer advice?

I'm attempting to create an auto-complete feature for a forum (similar to the tags below) that will function within LimeSurvey. I am fairly new to this, so please provide explanations as if you were explaining it to a 5-year-old :) My objectives are: ...

Struggling to retrieve information from MongoDB database for the web application

As someone new to the realm of MongoDB, I have been working on a web application that requires data storage. To handle this, I set up an HTTP server using Node.js on localhost:3000. Additionally, I created a virtual development environment using Vagrant an ...

What are the steps to launch a Next.js application on cPanel hosting?

Currently, I am faced with the task of deploying a Next.js application on cPanel. Node and npm have been successfully installed. Could you kindly guide me on how to deploy the Next.js app using this configuration? In my attempt to build the app in the cPa ...

When attempting to perform a GET request for registry.npmjs.org/react, `create-react-app` becomes un

I'm embarking on my first project using create-react-app, but I've encountered an issue with a spinning spinner that consists of just a period next to react. > npx create-react-app github-finder --verbose Creating a new React app in C:\d ...

Javascript: Uncaught TypeError - Unable to assign value to non-existent property

I am having an issue with assigning a value to a textbox, and I keep getting this error. Here is my code: This is the textbox in question: <input id="Text1" type="text" runat="server"/> Here is the dropdown list used in the function: <select i ...

Generate real-time dynamic line charts using data pulled directly from a MySQL database

I am in search of guidance on developing a real-time line chart that can dynamically update based on data fetched from MySQL. I need an example or reference on how to achieve this functionality without having to refresh the webpage every time new data is ...

Enable a VueJS directive on-the-fly from a separate directive

My goal is to simplify the process of binding a form control to vuejs by creating a directive that handles all necessary events for tracking changes in a form field. Rather than manually adding multiple event listeners like this: <input type="text" na ...

After executing webpack, it has been noticed that one of the dist files consistently ends up empty

As someone who is new to webpack, I have successfully used the quick start guide to process a simple JS file from src to dist. Everything was working fine. However, I encountered an issue when trying to process more than one JS file. The original tutorial ...

Is there a Node Package available for storing data indefinitely?

When I execute my code, I need to store a variable permanently. Is there a node package or another method to achieve this? I want to ensure that I can access the stored data even after restarting my server. For instance, in my file named "runMe.js": var ...

`[email protected]` to run the command `node-pre-gyp install --fallback-to-build`

Encountering an error while trying to install bcrypt on my Windows machine with the following versions: node v8.9.4 npm v5.6.0 bcrypt v1.0.3 During the installation process, I received the following error message: npm ERR! node-pre-gyp install --fal ...

AngularJS Update Parent-Child Relationship: Enhancing the Details

When Panel header is clicked, I want to update the respective Panel body with the corresponding data. In my Angular code on Plunker, clicking "Test1" should only update "Test1detail" in the body. Click here for the Plunker Here's the code snippet fr ...

Tips for transferring data to the next page with JavaScript AJAX

I am working on a webpage that includes an html select element <pre> $query = mysql_query("select * from results"); echo "<select id='date' onchange='showdata()' class='form-control'>"; while ($arr = mysql_fetch_a ...

Utilizing custom links for AJAX to showcase targeted pages: a beginner's guide

I am putting the final touches on my website and realized that it may be difficult to promote specific sections of the site because the browser address never changes. When visitors click on links, they open in a div using Ajax coding. However, if I want to ...

Error: Babelify unexpectedly throws a token mismatch in React "return" statement

Starting out with learning React, I encountered some issues in my development environment. Here is the code snippet that I am using, directly from the ReactJS tutorial available at https://reactjs.org/docs/components-and-props.html: --package.json: ...

Guide on how to call a function in ascx code-behind using JavaScript within the framework of DotNetN

Currently, I am facing an issue with my module that involves submitting data to a SQL table in a database using code behind. My validation is done through javascript, and when a button is clicked and the data is valid, a div is displayed. However, the pr ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

showing the chosen item in a Bootstrap dropdown [limited to the first menu option and using the attr() method]

Is there a way to dynamically display the selected menu option using the bootstrap drop down? Initially, I was able to select the first menu option and apply it to the bootstrap drop-down button. However, I encountered an issue where I cannot change the ...

Heroku is rejecting the Discord token, but it is functioning properly in Visual Studio Code

I am facing an issue with an invalid token error on Heroku, even though the token in my main.js file on Git is the same as the one I have in Visual Studio Code. Interestingly, Heroku claims it's an invalid bot token while the Discord bot token from VS ...

Deliver an intentionally bogus HTTP response using Express

I'm currently working on creating test cases for a web application and I am interested in testing how well the client can handle invalid HTTP responses. Can you provide some suggestions on how to purposely mess up a response so that it is no longer va ...