Reputation: 925
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!
Upvotes: 0
Views: 3013
Reputation: 263
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.
Upvotes: 2