Tips for accessing a file in AngularJS

Can AngularJS be used to read files? I am interested in placing the file within an HTML5 canvas for cropping purposes.

I was considering implementing a directive. Below is the JavaScript code that I plan to include in my directive:

function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

Answer â„–1

A good approach to using directives is demonstrated below:

.directive("ngFileSelect",function(){    
  return {
    link: function($scope,el){          
      el.bind("change", function(e){          
        $scope.file = (e.srcElement || e.target).files[0];
        $scope.getFile();
      });          
    }        
  }
})

For a live example, visit http://plnkr.co/edit/y5n16v?p=preview

Credit goes to lalalalalmbda for sharing this resource.

Answer â„–2

After incorporating Cherniv's code, I have consolidated it into a directive:

.directive('fileSelect', ['$window', function ($window) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, el, attr, ctrl) {
            var fileReader = new $window.FileReader();

            fileReader.onload = function () {
                ctrl.$setViewValue(fileReader.result);

                if ('fileLoaded' in attr) {
                    scope.$eval(attr['fileLoaded']);
                }
            };

            fileReader.onprogress = function (event) {
                if ('fileProgress' in attr) {
                    scope.$eval(attr['fileProgress'], 
                    {'$total': event.total, '$loaded': event.loaded});
                }
            };

            fileReader.onerror = function () {
                if ('fileError' in attr) {
                    scope.$eval(attr['fileError'], 
                    {'$error': fileReader.error});
                }
            };

            var fileType = attr['fileSelect'];

            el.bind('change', function (e) {
                var fileName = e.target.files[0];

                if (fileType === '' || fileType === 'text') {
                    fileReader.readAsText(fileName);
                } else if (fileType === 'data') {
                    fileReader.readAsDataURL(fileName);
                }
            });
        }
    };
}]);

To utilize the directive, follow these steps:

<input type="file" ng-model="file.data" 
       file-select="data" 
       file-loaded="myLoaded()"
       file-error="myError($error)" 
       file-progress="myProgress($total,$loaded)">

"file.data", "myLoaded", "myError", and "myProgress" should be defined in the enclosing scope for proper functionality.

Answer â„–3

Reading Files in Angular.

link: function(scope, element, attrs) {
            element.on('change', function(e) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    scope.$apply(function() {
                       scope.onReadFile({$content:e.target.result});
                    });
                };
                reader.readAsText((e.srcElement || e.target).files[0]);
            });
        }

Check out a live example here: Live Demo On Plunker

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

retrieving embedded content from an iframe on Internet Explorer version 7

Need help with iframe content retrieval $('.theiframe').load(function(){ var content = $(this.contentDocument).find('pre').html(); } I'm facing an issue where the iframe content is retrieved properly in FF, Chrome, and IE 8,9 ...

Build a Docker container for a project that requires utilizing yarn link for dependencies

While working on my NextJS project, I made the decision to utilize yarn as my package manager and utilized yarn link for import aliases/absolute imports. This feature of yarn is quite handy and is recommended for managing aliases within a project. However, ...

The presence of a nested Jade object in a JSON file does not result in being

Having trouble rendering a json object with nested data, When trying to iterate through each prod in order.productOrder, it doesn't display prod.name... JSON {    "id": "57bf5800473ffcd9bec12845",    "userId": "57988bf249c8791e403ea6f0",    ...

javascript utilize bluebird promise to asynchronously retrieve the first file from a given list

I am currently working on implementing promises in JavaScript to retrieve the first available file from a list of paths (for example, ["c:\\temp\\test1.json", "c:\\temp\\test2.json"]). The goal is to identify and ret ...

Ensure that a div remains active even after it has been selected through AJAX using jQuery

I am currently utilizing ajax to display information from a database. The application I am working on is a chat app, where clicking on a specific conversation will append the data to a view. The structure of my conversation div is as follows: <div clas ...

When the PHP response is received by AJAX, an error occurs due to a failed JSON parsing request

Every time I try to run my small JavaScript code with an AJAX call to PHP, it keeps coming back with a JSON parser error. In the PHP code, I can see that the JSON is populated with an array like this: json encode: {"Year":"2012","Make":"Ford","Model":"Tau ...

"Exploring the functionality of Vue JS2 checkboxes within a parent and

I am working with a complex nested list structure: <ul> <li v-for="subregion in continents"> <input type="checkbox" :id="subregion[0].subregion" > <label :for="subregion[0].subregion">{{ subregion[0].subregion }}< ...

Can anyone offer any suggestions for this issue with Angular? I've tried following a Mosh tutorial but it's

Just finished watching a video at around 1 hour and 35 minutes mark where they added the courses part. However, I encountered an error during compilation. ../src/app/app.component.html:2:1 - error NG8001: 'courses' is not recognized as an elemen ...

Redirecting visitors to a specific section of the website as soon as they enter the site

Currently, I am utilizing a jquery plugin known as Ascensor which can be found at this link: This plugin is designed for creating one-page websites with smooth scrolling capabilities both vertically and horizontally. It operates using a coordinate system ...

Embedding $sce functionality within a controller

I am facing a challenge where I have HTML content coming in as a string and I need to render it. After exploring options, I am considering using ng-bind-html, which requires $sce to be injected into the controller. Most of the examples I found online show ...

Looking to showcase website HTML code by simply clicking on a banner image?

I am looking to implement a feature where banner HTML code is displayed in a popup on website when the banner is clicked. For instance, an example of a banner could be: <img src="https://myweb.com/images/banners/1.gif"> Upon clicking the banner im ...

What is the best way to delete stored angularjs files permanently?

My web application, built on AngularJS, has certain functionalities that I have hidden from users. While the controls have been successfully hidden in the updated version of the file, there are still some users with the old file who can access these undesi ...

"Encountering a problem with the Flicker API while trying to view personal

I've been attempting to retrieve my personal photos using the following function with a node package obtained from this source https://www.npmjs.com/package/flickrapi\ When trying to access pictures of another user like 136485307@N06 (Apollo Im ...

Is there a way to modify the FixedTableHeader jQuery plugin to include a fixed first column in addition to the fixed header?

I've been experimenting with a jQuery plugin I found at to create a stylish table with fixed headers, sorting options, and other interesting features. While the plugin is great, I also considered using jqGrid for its impressive capabilities. However, ...

retrieve room from a socket on socket.io

Is there a way to retrieve the rooms associated with a socket in socket.io version 1.4? I attempted to use this.socket.adapter.rooms, but encountered an error in the chrome console: Cannot read property 'rooms' of undefined Here is the method I ...

What could be causing my data to undergo alterations when transitioning from a frontend form submission to a backend API?

In my experience with Next.js 13 and Prisma, I encountered a peculiar issue. I had set up a basic form to collect user information for an api request. Oddly enough, when I printed the data right before sending it, everything seemed fine. However, upon arri ...

Extract form input to utilize in nodemailer

Currently I am working on a form implementation where I intend to utilize nodemailer for sending test emails to myself. My goal is to have the email inputted into the form dynamically appear in both the "to" and "subject" fields when the user submits the f ...

Chrome mistakenly identifying octet-stream as a .png image

My application incorporates the use of Google Maps API V3 and ASP.Net, utilizing OverlayView to customize icons on the map. The icon's image is configured within the onAdd event by dynamically adjusting the background CSS property using JavaScript. T ...

How to style TextInput to display dollar amounts when using onChangeText and Redux in React Native

Struggling to format number input in a TextInput using the onChangeText function in React Native with Redux. Tried using .toFixed(2) function, but encountering an issue where it interprets the next digit as the first decimal and rounds back to 0 due to Re ...

How to use PHP and JavaScript to update a location marker on Google Maps

I'm new to web development and in need of some help, please. I have a code that is supposed to update the marker location with coordinates retrieved from a database. <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AP ...