AngularJS simple image preview on file input - angularjs

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]);
}

Related

Some problems in the deployment of the dropzone in AngularJS 1.4.9

When I try to erase the image in the dropzone there are traces of it, which prevent me from uploading it again, unless I upload and erase another image before. I'm using the 1.4.9 version of AngularJS
//controller
app.controller('AppController',function($http){
var ctrl = this;
ctrl.data = { upload:[] } // <= upload data get pushed here
ctrl.upload= function(){
console.log(ctrl.data);
$http({
method : 'POST',
url : 'upload.php',
data : ctrl.data,
}).success(function(data){
alert(data);
});
}
ctrl.delete= function(){
ctrl.data = { upload:[] };
}
});
//and here the directive who controls the upload an the image base64 conversion
app.directive('dropZone',[
function(){
var config = {
template:'<label class="drop-zone">'+
'<input type="file" accept="jpg,png" />'+
'<div ng-transclude></div>'+ // <= transcluded stuff
'</label>',
transclude:true,
replace: true,
require: '?ngModel',
link: function(scope, element, attributes, ngModel){
var upload = element[0].querySelector('input');
upload.addEventListener('dragover', uploadDragOver, false);
upload.addEventListener('drop', uploadFileSelect, false);
upload.addEventListener('change', uploadFileSelect, false);
config.scope = scope;
config.model = ngModel;
}
}
return config;
// Helper functions
function uploadDragOver(e) { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }
function uploadFileSelect(e) {
console.log(config.scope.app.data.upload);
if (config.scope.app.data.upload.length+1==1) {
/* console.log("Hola"+config.scope.app.data.upload.length); */
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer ? e.dataTransfer.files: e.target.files;
for (var i = 0, file; file = files[i]; ++i) {
/* console.log(file); */
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
// Data handling (just a basic example):
// [object File] produces an empty object on the model
// why we copy the properties to an object containing
// the Filereader base64 data from e.target.result
var data={
data:e.target.result,
dataSize: e.target.result.length
};
for(var p in file){ data[p] = file[p] }
config.scope.$apply(function(){ config.model.$viewValue.push(data) })
}
})(file);
reader.readAsDataURL(file);
}
}else{console.log("Solo puedes subir una foto.")}
}
}
])
What i expect
When you delete the image in the dropzone, you can upload it again. That is the expected result.

Binding Directive attribute to Controller not working

I am currently stuck in a situation and the scenario is I want to bind the directive to my HTML but nothing works I want to bind directive scope with HTML
this is what I am doing:
this is my directive what I want is to bind the attribute file to my HTML so I can get the name of file and modified date
.directive("fileinput", [function() {
return {
scope: {
file: "=",
filepreview: "="
},
link: function(scope, element, attributes) {
element.bind("change", function(changeEvent) {
scope.file = changeEvent.target.files[0];
scope.filepreview='';
var reader = new FileReader();
reader.onload = function(loadEvent) {
scope.$apply(function() {
console.log(scope.file)//printing file value but not reflect in html
scope.filepreview = loadEvent.target.result;
var ctx = document.getElementById('myCanvas').getContext('2d');
ctx.clearRect(0, 0, 300, 130);
var img = new Image();
img.src = scope.filepreview ;
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
});
}
reader.readAsDataURL(scope.fileinput);
});
}
}
}])
index.html
<div class='form-group required'>
<label>{{file.LastModified}}</label>
<input type="file" fileinput="file" filepreview="filepreview"/>
</div>
Nothing happens when I upload file but in directive, I am getting file
any help will be appreciated.
your directive scope has "file" object but you are using "fileInput" to get the file , Can you try below code
<input type="file" fileinput file="file" filepreview="filepreview"/>

<input> file is not updating/wroking properly in AngularJs

I am trying to write a directive for <input> type file. This directive will handle file change event and I am trying to return following object as a model.
{ fileName: element[0].files[0].name, fileAsBuffer: e.target.result }
My directive code
"use strict";
(function() {
angular
.module("fileUploadApp")
.directive("customFileChange", customFileChange);
customFileChange.$inject = ["$parse"];
function customFileChange($parse) {
return {
restrict: "A",
link: function(scope, element, attrs) {
var model = $parse(attrs.customFileChange);
var modelSetter = model.assign;
element.bind("change", function() {
scope.$apply(function() {
var reader = new FileReader();
reader.onload = function(e) {
var fileModel = {
fileName: element[0].files[0].name,
fileAsBuffer: e.target.result
};
modelSetter(scope, fileModel);
}
reader.onerror = function(e) {
console.log(e.target.error);
}
reader.readAsArrayBuffer(element[0].files[0]);
});
});
}
};
}
})();
My html
<input type="file" name="name" data-custom-file-change="vm.newDocument.attachment" />
<p>{{vm.newDocument.attachment.fileName}}</p>
Problem:
First time when I upload a file, It is not showing anything in
<p>{{vm.newDocument.attachment.fileName}}</p>
Second time if I upload another file, the It is showing the first
file name in <p>{{vm.newDocument.attachment.fileName}}</p>
JS Bin
You need to trigger the digest cycle from inside the callback function itself.
For example:
reader.onload = function (e) {
var fileModel = { fileName: element[0].files[0].name, fileAsBuffer: e.target.result };
scope.$apply(function () {
modelSetter(scope, fileModel);
});
};
Demo: https://jsbin.com/nicocosige/1/edit?html,js,console,output

Force image orientation angularjs

I have this odd behavior when I upload an image and if this image size has more height than with I get the image rotated 90 degrees.
check this fiddle that's using ngImgCrop and this is the image that I'm uploading
the code of the ngDmgCrop it's pretty standard:
angular.module('app', ['ngImgCrop'])
.controller('Ctrl', function($scope) {
$scope.myImage='';
$scope.myCroppedImage='';
var handleFileSelect=function(evt) {
var file=evt.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function (evt) {
$scope.$apply(function($scope){
$scope.myImage=evt.target.result;
});
};
reader.readAsDataURL(file);
};
angular.element(document.querySelector('#fileInput')).on('change',handleFileSelect);
});
how can I fix this behavior?
You'll have to parse the exif data in the image header, examine the Orientation tag, and rotate accordingly.
I just solved the same problem with this library: Javascript Load Image
In your app.js
var handleFileSelect = function(evt) {
var target = evt.dataTransfer || evt.target;
var file = target && target.files && target.files[0];
var options = {canvas:true};
var displayImg = function(img) {
$scope.$apply(function($scope){
$scope.myImage=img.toDataURL();
});
}
loadImage.parseMetaData(file, function (data) {
if (data.exif) {
options.orientation = data.exif.get('Orientation');
}
loadImage(file, displayImg, options );
});
};
Demo : Plunker
Cheers.

convert image to base64 in 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

Resources