0

I want upload file/image with input type="file" of HTML5 using AngularJs and when the user upload the image show the preview. So I created my custom directive in this way:

var modulo = angular.module('myApp', []);

modulo.directive('fileModel', function () {
    return {
        restrict: 'AEC',
        link: function(scope, element, attrs) {
            element.bind('change', function (event) {
                //Take the object
                var fetchFile = event.target.files[0];
                //emit the object upward
                scope.$emit('fileSelected', fetchFile);
            });            
        }
    };
});

Now I show my controller when I take the object (file/image) and with this controller I want show the preview.

modulo.controller('myController', function ($scope, $http) {

    var files;

    $scope.$on('fileSelected', function(event, fetchFile) {
        //Receive the object from another scope with emit
        files = fetchFile;
        var reader = new FileReader();

        reader.onloadend = function () {
            //Put the object/image in page html with scope
            $scope.content = reader.fetchFile;
        }; 
    });
});

Finally I show my html page where I want show the preview down the input file.

<html ng-app="myApp">
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="js/libs/angular.js/angular.js"></script>
        <script src="script.js"></script>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    </head>
    <body ng-controller="myController">

        <h1>Select file</h1>
        <input type="file" file-model/>
        <img ng-src="{{content}}"/>
        <div>
            <button ng-click="send()">
                send
            </button>
        </div>
    </body>
</html>

In this way I don't obtain the preview also in this snippet there isn't the function for send the image with Json that I'll do. How can I fix the question? Thanks!

1 Answer 1

2

You have to convert the file data that is read to Base 64 string format. Then you can use that base 64 data to show the image.

<img src='data:image/jpeg;base64,<!-- base64 data -->' />

You can easily transfer this base 64 data to server since it is just a string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.