Managing file sizes on the client side prior to transferring them to the server side

I am looking to implement client-side validation for file size. The current code only handles success, but I also want to address file size limitations. Right now, if a file exceeds 2MB, it results in a 500 (Internal Server Error) behind the scenes.

Is there a way to manually handle this and display an error message such as "Max file size should be 2MB"?

Thank you in advance

Note: The snippet below is written in AngularJS

file.upload(url, function(data) {
    if(data.success !== true) {
        $scope.$apply(function() {
            $scope.design.pdf.status = '';
            $scope.errors.pdf = data.data;
        });
        return;
    }
    $scope.$apply(function() {
        $scope.design.pdf = {
            status: 'uploaded',
            file: data.data.name,
            name: data.data.original,
            size: data.data.size
        }
    });
});

Answer №1

It seems like you are using an input type='file' button. One way to get the size is by creating a directive that binds to the button when it changes.

The directive can be implemented as follows:

app.directive('customUpload', function(){
  return {
    restrict: 'A',
    link: function(scope, element, attrs){
        element.on('change', function(){
          //size in bytes
          var size = element[0].files[0].size;
          console.log(size);
          //perform actions with the file
        });
      }
    };
});

And in the HTML:

<input type='file' custom-upload>

You can also find the complete code in this Plunker demo: http://plnkr.co/edit/GB6MFOWMbjOA7obFBq83?p=preview

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

Express router is unable to process POST requests, resulting in a 404 error

I am having trouble fetching POST requests to my Express router. While my many GET requests work fine, this is my first POST request and it is not functioning correctly. Here is a snippet of my frontend code: export async function postHamster(name, age) ...

ReactJs - SyntaxError: The JSX content is not properly terminated

I'm just starting out with ReactJs and have come across an issue that I can't seem to figure out. Here's my code snippet: var ListComponent = React.createClass({ render: function() { return ( <li>{this.props.va ...

Utilizing ES6, accessing the first element of an array of objects

How can I access the values of the first or a specific object in an array based on an index using ES6? arrayOne =[ { child: [ {e1: 'ABCD', e2: 'BCDF'}, {e1: '1234', e2: '5689'}, {e1: 'QAZ ...

Techniques for finding the total value of a JSON array

After retrieving values from a database, I am using them in JSON/javascript as an array. For example, see The issue arises when trying to calculate the sum of the array elements. I attempted to solve it with this code: var obj1 = JSON.parse(data); var m ...

Modify the content of a tooltip when hovering over the session times button

My website coded in ASP.Net is able to generate buttons which contain the following HTML code: <a id="1173766" val="248506" titletext="<b>Click to book online for ABC Cinemas</b><strong>$10 tickets </strong>: Preview Screening& ...

Implementing Autocomplete feature in Reactjs with Ant Design Library

In my React application, I created an autocomplete feature with a list of options for the user to select from. Example in Action: Click here to see the demo List of available options: const options = [ { label: "hello", value: "1" ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Next.js - utilizing dynamic API routes within nested folders

Currently, I am working on developing a basic API that reads a local JSON file. My goal is to create a dynamic API that can adjust based on the specific calls it receives. Within my API folder structure, I have: api --book ---[id].js ----content -----[id ...

Is there a way to refresh CSS styles when the window width is adjusted?

Is there a way to refresh CSS styles when the window width changes? I attempted this method, but unfortunately it did not work as expected. A simple refresh (F5) helps to rectify the CSS tags. jQuery(function($){ var windowWidth = $(window).width(); ...

Variable unique to the specific function in universal function

Can you explain why the alert displays "AAA" instead of "BBB"? http://jsfiddle.net/Lp4cS/ var z = "AAA"; function xx() { var z = "BBB"; yy(); } function yy() { alert(z); } xx(); ...

The error encountered is: "TypeError: req.flash does not exist as a function in NodeJs

When it comes to working with Registration on a Site, the Validation process is key. In this case, mongoose models are being used for validation and an attempt is being made to utilize Flash to showcase error messages within the Form. However, there seems ...

Using PHP to create multiple div elements and then concealing them all

I'm having an issue with the hide feature not working. My intention is to hide each dynamically generated div and gain control over them, but the problem seems to lie in the div id incrementing. Any assistance would be greatly appreciated! <?php $ ...

The element type is not valid: it should be a string for built-in components or a class/function for composite components, but it is currently an object in a React project

In the process of developing a React app to explore MUI capabilities, I encountered an error in my browser: The issue reported is: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but rec ...

Strange padding issue found on View component in React Native Web when using Edge browser

While developing a Button in react native for the web, I noticed an unusual padding issue when viewing the button in Edge. Despite my efforts to debug, I have not been able to find a solution. Strangely, the button appears correctly on Android and Firefox. ...

Having difficulty with printing a particular div

I need help with printing a specific div containing checkboxes using jQuery. The checkboxes are initially checked based on data from a database, but when I try to print the div, the checkboxes remain unchecked in the print view. Below is the code snippet ...

What is the best way to use jQuery ajax to send various row identifiers when updating table data on another PHP page by selecting checkboxes?

When I select both of the green checkboxes, only the most recent table id is sent. The code below includes both the checkbox markup and jQuery function. Checkbox: <div class='md-checkbox has-success'> <input type='checkbox&apo ...

Updating the Keycloak token in VueJS using keycloak-js even when it is still valid

I have implemented a VueJS frontend connected to Keycloak using keycloak-js openid, without using the implicit flow https://i.sstatic.net/BxhJh.png Currently, there is a scenario in which the Backend NodeJS adds groups to a user in Keycloak. However, in ...

Effortlessly switch between multiple divs with jQuery

I am working on a functionality where multiple divs should be displayed or hidden based on the button clicked. Initially, all buttons and divs are visible. Upon clicking a button, only the corresponding div should be visible. Subsequent clicks on other but ...

Leveraging JS Variables within Twig Template

I am trying to incorporate a JavaScript variable into Twig. Despite attempting to implement the solution mentioned here, my code below does not render the map properly. If I remove the part between "var polylineCoordinates" and "polyline.setMap(map);", th ...

The size of Bootstrap 3 columns adjusts dynamically based on the width of the window as the page is being

I am facing an issue with the layout of my bootstrap site when resizing the 3 horizontal columns based on the window size upon page load. Currently, I have a script that adjusts the height of each column to match the tallest one so they appear uniform whe ...