convert image to base64 in angularjs - angularjs

I have a requirement where user will upload their image and i have to convert it into something and send it to .Net REStful service. I am new to angular js. Could someone please help

Answer from here https://stackoverflow.com/a/24880314/625189
I would recommend you to use
https://github.com/ninjatronic/angular-base64.
After following instructions for using this library, you can simply
call:
var imageData=$base64.encode(image);
Don't forget to inject in your module:
.module('myApp', ['base64'])

You can use the angular custom directive to convert the image base64.
directive.js
myApp.directive('imgUpload', ['$rootScope',function (rootScope) {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
var canvas = document.createElement("canvas");
var extensions = 'jpeg ,jpg, png, gif';
elem.on('change', function () {
reader.readAsDataURL(elem[0].files[0]);
var filename = elem[0].files[0].name;
var extensionlist = filename.split('.');
var extension =extensionlist[extensionlist.length - 1];
if(extensions.indexOf(extension) == -1){
alert("File extension , Only 'jpeg', 'jpg', 'png', 'gif', 'bmp' are allowed.");
}else{
scope.file = elem[0].files[0];
scope.imageName = filename;
}
});
var reader = new FileReader();
reader.onload = function (e) {
scope.image = e.target.result;
scope.$apply();
}
}
}
}]);
Html:
<div class="input-group">
<input id="image" class="hidden" type="file" img-upload ng-model="imageName" name="imageName">
<img ng-src="{{image}}" height="100" width="100" ng-show="image"/>
<label for="image" class="btn btn-success btn-xs pull-center" name="upload" Value="">Upload Photo</label>
</div>
Now you need to add your code in controller which works for storing image or file in database.

If your image data is already in base64, try
<img alt="{{p.alt}}" data-ng-src="{{'data:image/png;base64,'+p.Photo}}" class="photo" />

Code to upload the image in 64 bit in Angularjs
Html code
<div class="col-md-8">
<img ng-src="data:image/png;base64,{{model.Logo}}" id="photo-id" />
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this)" id="photo-upload" />
</div>
Angular code:
$scope.uploadFile = function (input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(input.files[0]);
reader.onload = function (e) {
$('#photo-id').attr('src', e.target.result);
var canvas = document.createElement("canvas");
var imageElement = document.createElement("img");
imageElement.setAttribute = $('<img>', { src: e.target.result });
var context = canvas.getContext("2d");
imageElement.setAttribute.load(function()
{
debugger;
canvas.width = this.width;
canvas.height = this.height;
context.drawImage(this, 0, 0);
var base64Image = canvas.toDataURL("image/png");
var data = base64Image.replace(/^data:image\/\w+;base64,/, "");
$scope.model.Logo = data;
});
}
}
}
for more go to link:
http://vikasbishtangular.blogspot.in/2017/04/code-to-upload-image-in-64-bit-in.html

Related

Angularjs pdf thumbnail is not showing after file upload

When I am trying to upload pdf file, thumbnail is not showing after file upload. But it shows the thumbnail for video and ppt. I have created custom directive for thumbnail.
Here is my code,
my html code:
<div class="col-md-5" style="overflow: hidden">
<div style="display: inline-block" ng-if="thumbfilelink" ng-thumb="{ file: thumbfilelink, height: 100, width:75, fromServer:true, fileURL:thumbfilelink }"></div>
<div style="display:inline-block" ng-if="!thumbfilelink&&!item.isError">
<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><span class="sr-only">Loading Preview...</span>
</div>
<span style="position: absolute; margin-left: 15px;" ng-bind="item.file.name"></span>
</div>
Controller:
uploader.onSuccessItem = function (fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
$scope.$parent.delegate.onAttachmentUpload(response);
growl.addSuccessMessage($translate.instant('fileUpload.singlefileSuccess'));
// $scope.thumbfilelink=response.link;
$scope.thumbfilelink=$rootScope.app.coreURI +'file/image/'+response.id+'/preview';
};
Custom Directive:
return {
restrict: 'A',
template: '<div>' +
'<canvas class="ac-thumb" style="width:75px" />' +
'' +
'</div>',
transclude:true,
link: function (scope, element, attributes) {
if (!helper.support) return;
var canvas = element.find('canvas');
var reader = new FileReader();
if(params.fromServer) {
var img = new Image();
img.onload = onLoadImage;
img.src = params.fileURL;
}
else {
if (!helper.isFile(params.file)) return;
if (!helper.isImage(params.file)) return;
reader.readAsDataURL(params.file);
reader.onload = onLoadFile;
}
function onLoadFile(event) {
var img = new Image();
img.onload = onLoadImage;
img.src = event.target.result;
}
function onLoadImage() {
var width = params.width || this.width / this.height * params.height;
var height = params.height || this.height / this.width * params.width;
canvas.attr({width: width, height: height});
canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
} }
};
}]);
}).call();
you need to manipulate the event.
onChange event.
use on-change event, handle it as directive with passed controller function which will be called via bind.

NgModel not found while create directive

Here is my directive fileUpload for validation of image extenstion. I am not getting what is missing here. (Missing Required Controller Controller 'ngModel', required by directive 'fileUpload', can't be found! ) Please if any one can look in to this.
I found so many reference to the same question but no luck . please dont mark this as repeat question.
App.directive('fileUpload', function () {
return {
scope: true, //create a new scope
require: 'ngModel',
link: function (scope, el, attrs,ctrl) {
ctrl.$validators.images = function(modelValue, viewValue) {
console.log(modelValue);
console.log(viewValue);
};
ngModel.$setValidity('extension', true);
el.bind('change', function (event) {
var files = event.target.files;
var validFormats = ['jpg', 'jpeg', 'png', 'gif'];
var validSize = 500000;
for (var i = 0;i<files.length;i++) {
var ext = files[i].name.split('.');
var size = files[i].size;
if (ext !== undefined) {
var isExist = validFormats.indexOf(ext[1].toLowerCase()) >= 0 ? 1 : 0;
if (isExist == true && validSize >= (size)) {
ngModel.$setValidity('extension', true);
} else {
ngModel.$setValidity('extension', false);
}
}
//emit event upward
scope.$emit("fileSelected", { file: files[i] });
}
});
}
};
});
Input :
<div class="form-group has-feedback" style="margin-left: 10px;">
<input name="file" type="file" ng-model="images" accept="image/*" multiple="true" file-upload />
<div style="color:grey; font-size: 12px;">
Extensions : jpg , jpeg , png , gif<br>
Size : 500KB
</div>
<div ng-messages="frmSupportPanelist.file.$error" ng-if="frmSupportPanelist.file.$touched">
<label id="message-required-error" class="validation-error-label" for="file" ng-message="extension">Please select valid Image </label>
</div>
</div>

AngularJS simple image preview on file input

Can someone tell me why this code does not work?
this my preview area: <div class="preview"><img src="" alt=""></div>
and this my input:<input type="file" file-input> and follow my directive code:
var cmos = angular.module('cmos', ['simditor']);
// controller
cmos.controller('cmosCtrl', function( $scope ){}
// directive
cmos.directive("fileInput", function( $parse ){
return{
link: function($scope, element, attrs){
element.on('change', function(event){
var files = event.target.files;
var reader = new FileReader();
var img = document.querySelector(".preview > img");
reader.addEventListener("load", function(){
img.src = reader.result;
}, false);
if(files){
reader.readAsDataURL(files[0]);
}
// console.log(files[0]);
});
}
}
});
When I insert an image on input would like to take an image and show it to preview area.
you can use $scope like this..
<div class="preview"><img src="{{imageUrl}}" alt=""></div>
and in js.
var files = event.target.files;
var reader = new FileReader();
reader.addEventListener("load", function(){
$scope.imageUrl = reader.result;
}, false);
if(files){
reader.readAsDataURL(files[0]);
}

How to shorten the length of the url while uploading the image using fileread directive?

When we push The Image Store the url in base 64 format, it becomes very big. How to shorten this base 64 url ?
I am using the file read directive for uploading the image. Check the plunker. Please help how to do this.
<body ng-controller="MainController">
<input type="file" name="image" ng-model="companyItem" fileread="companyItem" required>
<img ng-src="{{companyItem}}" style="width:100px;height:100px"/>
<button type="button" ng-click="save(companyItem)">save</button>
<script>
app.controller("MainController",function($scope){
$scope.data=[]
$scope.companyItem={}
$scope.save=function(companyItem){
$scope.data.push($scope.companyItem)
console.log($scope.data)
$scope.companyItem={}
}
})
</script>
</body>
Script
var app=angular.module("select",[]);
app.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}]);
`https://plnkr.co/edit/JRxB4uNlCbBrkfkwUwMv?p=preview

How to display the image name of uploaded image in angularjs

I am uploading an image and in one td I also put the image name. But my problem is when I upload a image, the image name repeats in all the rows which should not. What is wrong with this? Thanks.
This is my fiddle link: http://jsfiddle.net/DharkRoses/g31ykfy8/
sample code:
$scope.fileReaderSupported = window.FileReader != null;
$scope.photoChanged = function (files, index) {
if (files != null) {
var file = files[0];
var index = this.$index;
$scope.imgName = files[0].name;
if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
$timeout(function () {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (e) {
$timeout(function () {
$scope.thumbnail[index] = {dataUrl: e.target.result};
});
}
});
}
}
};
You need to create a same size of array for file names and based on index you need to push file names in photoChanged event.
Below is the working code for same.
angular.module('test', []);
angular.module('test').controller('UploadCtrl', function ($scope, $timeout,$parse) {
$scope.imgName ='';
$scope.thumbnail = {
dataUrl: []
};
$scope.fileNames = [,,,,];
$scope.fileReaderSupported = window.FileReader != null;
$scope.photoChanged = function (files, index) {
if (files != null) {
var index = this.$index;
var file = files[0];
$scope.fileNames[index] = files[0].name;
$scope.$apply();
if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
$timeout(function () {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (e) {
$timeout(function () {
$scope.thumbnail[index] = {dataUrl: e.target.result};
});
}
});
}
}
};
});
The markup looks something like below.
<div ng-app="test">
<div ng-controller="UploadCtrl">
<table>
<tr ng-repeat="i in [1, 2, 3, 4]">
<td>{{i}}</td>
<td>
<input type="file" name="file" onchange="angular.element(this).scope().photoChanged(this.files)" />
<img ng-src="{{ thumbnail[$index].dataUrl }}" height="50px" />
</td>
<td>
{{fileNames[$index]}}
</td>
</tr>
</table>
</div>
</div>
The working fiddle can be found here.

Resources