Is it possible to convert file object to image object?
I need width and height from file (which is an image), here is my code:
view:
<button id="image_file" class="md-button md-raised md-primary"
type="file" ngf-select="uploadFile($file)">
SELECT FILE
</button>
<md-input-container>
<div class="raised">
<input id="image_file_name" type="text" ng-model="vm.file.name"></input>
</div>
</md-input-container>
controller:
app.controller('imageController', function($scope, fileService) {
$scope.vm = {};
$('.intro').show(1000);
$scope.uploadFile = function(file) {
$scope.vm.file = "";
$scope.vm.file = file; //<---- for example here, how it should be done?
fileService.uploadFile($scope);
}
service:
angular.module('app')
.service('fileService', function ($http, validationService) {
this.uploadFile = function ($scope){
if (validationService.isFileValidate($scope)) {
$scope.vm.acceptableFormat = true;
} else {
$scope.vm.acceptableFormat = false;
}
};
});
The library already seems to give most of what you require. To read width and height properties of the file/image .
//Add accept option to filter only images
<button id="image_file" class="md-button md-raised md-primary"
type="file" accept="image/*" ngf-select="uploadFile($file)">
SELECT FILE
</button>
Controller
$scope.uploadFile = function(file) {
$scope.vm.file = "";
$scope.vm.file = file;
// show all file properties
console.log(file); // Show available properties
console.log(file.$ngfWidth +','+ file.$ngfHeight) // Your width and height
fileService.uploadFile($scope);
}
You should probably check out it's Features.
Related
In multiple image upload how to delete particular image if i click that image in angularjs.i have uploaded multiple image and i have textbox with every uploaded image.if i click image delete icon it removes the image with that textbox.my view code looks below
<input type="file" multiple file-upload /> {{files.length}}
<div ng-repeat="step in files">
<img ng-src="{{step.src}}" />
<input type="text" ng-model="comment[$index]"><br>
<input type="button" onclick="removeImage($index)" value="delete">
</div>
In my angular controller code looks like below
app.directive('fileUpload', function() {
return {
scope: true, //create a new scope
link: function(scope, el, attrs) {
el.bind('change', function(event) {
var files = event.target.files;
//iterate files since 'multiple' may be specified on the element
for (var i = 0; i < files.length; i++) {
//emit event upward
scope.$emit("fileSelected", {
file: files[i]
});
}
});
}
};
});
$scope.files = [];
$scope.$on("fileSelected", function(event, args) {
var item = args;
$scope.files.push(item);
var reader = new FileReader();
reader.addEventListener("load", function() {
$scope.$apply(function() {
item.src = reader.result;
});
}, false);
if (item.file) {
reader.readAsDataURL(item.file);
}
});
Instead of onclick use ng-click and use javascript splice function to remove an item from an array
<input type="button" ng-click="removeImage($index)" value="delete">
$scope.removeImage = function(index){
$scope.files.splice(index,1)
}
I am very new to front-end development and I thought it would be cool to add drag and drop to a current upload page. However after starting to hook everything up with ng-flow (a directive that assists with drag and drop) I cannot seem to make the connection on how to add the files to the file list. If you think I don't even need the directive and am just overkilling this and there is a simpler solution I would be willing to make changes as well. NOTE: I am giving only samples of the code so dont ding it for not compiling!
fileModelDirective:
app.directive('fileModel', ['$parse', '$log', '$confirm',
function ($parse, $log, $confirm) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
scope.sampleFile = model;
element.bind('change', function () {
// if the file open dialog is raised and the file name
// is cleared and cancel is pressed then a reset is needed
// document.getElementById('file-upload-name').innerHTML = "";
// document.getElementById('file-upload-btn').disabled = true;
// status always needs reset if choosing another file
scope.$apply(function () {
modelSetter(scope, element[0].files);
if (document.getElementById('file-upload').files) {
// This iterates over to see if the total files size is greater than 100MB
const maxFilesSize = 104857600;
var totalFilesSize = 0;
var numberOfDataSamples = element[0].files.length;
}
});
});
} // link
};
}]); // fileModel
fileMethod
$scope.uploadFile = function () {
console.log(flow)
var file = flow.file;
$scope.numberOfFiles = document.getElementById('file-upload').files.length;
$scope.filesTotalSize = 0;
for (var i = 0; i < document.getElementById('file-upload').files.length; i++) {
$scope.filesTotalSize = document.getElementById('file-upload').files[i].size + $scope.filesTotalSize;
}
fileUpload Service
app.service('fileUpload', ['$http', '$log',
function ($http, $log) {
this.uploadFileToUrl = function (file, uploadUrl) {
//$log.debug("file(s)");
//$log.debug(file);
var fd = new FormData();
angular.forEach(file, function (value, key) {
fd.append(key, value);
});
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
'enctype': "multipart/form-data"
}
})
}; // uploadFileToUrl
}]); // fileUpload
html
<div flow-init flow-files-submitted="$flow.upload()" class="ng-scope">
<div flow-drop>
<span for="file-upload"
class="btn btn-primary" flow-btn style="margin-top: 10px; ">Upload File
<input id="file-upload" type="file" multiple="multiple" file-model="sampleFile"
style="visibility: hidden; position: absolute;"></span>
<p flow-prevent-drop
flow-drag-enter="style={border: '5px dashed purple'}"
flow-drag-leave="style={}"
ng-style="style"
style="margin-top: 10px;width: 100%;min-height: 50px;">
Drag And Drop your file here</p>
<br>
<span ng-repeat="file in $flow.files track by $index">
{{file.name + ", " }}
</span>
<div style="margin-left: 2px; margin-top: 10px;">
<button id="file-upload-btn" class="btn btn-primary"
ng-click="showMask(); uploadFile();">
Upload
</button>
<button class="btn btn-primary" style="float: right;"
ng-click="navigateTo('/startup')">
Cancel
</button>
<button style="float: right; margin-right: 6px;" class="btn btn-primary"
ng-click="$flow.cancel()">
Clear
</button>
</div>
</div>
</div>
I'm just experimenting with a similar service. Taking angular Array of files, and pushing the items onto the javascript "file-upload".FileList array, but no luck, as the 'files' property is a readonly FileList object.
A pre-packaged solution:
http://blueimp.github.io/jQuery-File-Upload/angularjs.html
and it has drag and drop on to the whole page working.
This one: http://angular-file-upload.appspot.com/ even has Paste and access to Camera on mobile.
Your solution for adding files to the formData is good and inline with jquery ajaxSubmit form code
Maybe you could create a Plnk to collaborate on ...
formdata.append(a[i].name, a[i].value);
I have a page employee.html with a list of dependents and for each row (li) an inner button with the directive ng-click="editDependent({{dependent.id}})". That button tries to call a modal box.
The employee.html is loaded in a ui_view div from an index.html
I saw that each button in view source with chrome are correctly bound ng-click="editDepedent(1)" and so on.
But at the same time I have an error
angular.min.js:118 Error: [$parse:syntax] http://errors.angularjs.org/1.5.8/$parse/syntax?p0=%7B&p1=invalid%20key&p2=11&p3=editDependent(%7B%7Bdependent.id%7D%7D)&p4=%7Bdependent.id%7D%7D)
I'm trying to pass my dependent id to my modal and the previous scope also that contains the info about the employee. So how can I achieve this parameter passing?
This is my main controller
app.controller('EmployeeController', function ($scope, $stateParams, $uibModal, EmployeeService) {
if($stateParams.id){
EmployeeService.getEmployee($stateParams.id).then(function(employee){
$scope.employee = employee;
EmployeeService.setCurrentEmployee(employee);
});
}
$scope.editDependent = function(id){
if(id){
$scope.dependentid = id;
}
var uibModalInstance = $uibModal.open({
templateUrl : 'modal_dependent.html',
controller : 'DependentController',
scope: $scope
});
return uibModalInstance;
}
});
This is my dependent controller to catch the value
app.controller('DependentController', function($scope, $uibModal, $uibModalInstance, $stateParams, EmployeeService){
//Following line does not work because it gets the ID of employee which is passed by querystring
//var dependentID = $stateParams.id;
if($scope.dependentid){
var currentEmployee = EmployeeService.getCurrentEmployee();
//find the current dependent
for(var i = 0; i < currentEmployee.dependents.length; i++){
//*****************************************************
//Hardcoding 1 to test the dependent number 1 but it should be the dependent id parameter
if(currentEmployee.dependents[i].id == 1){
$scope.dependent = currentEmployee.dependents[i];
break;
}
}
}else{
$scope.dependent = { id : 0 };
}
$scope.editableDependent = angular.copy($scope.dependent);
//Submit button in modal
$scope.submitDependent = function(){
DependentService.saveDependent($scope.editableDependent);
$scope.dependent = angular.copy($scope.editableDependent);
$uibModalInstance.close();
}
});
UPDATE
employee.html
<form name="employee_form">
<div>
<h1> {{employee.name}} </h1>
<h3>Dependents</h3>
<button class="btn bgcolor-rb-main" x-ng-click="editDependent(0)">
Add new
</button>
<ul class="list-inline">
<li x-ng-repeat="dependent in employee.dependents">
<button x-ng-click="editDependent({{dependent.id}})">
Edit
</button><br>
<div>{{dependent.name}}</div>
</li>
</ul>
</div>
</form>
This is my modal_dependent.html
<div class="modal-header">
<h4>Dependent</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" id="txtName" x-ng-model="editableDependent.name" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" x-ng-click="discardChanges()">Discard</button>
<button type="submit" class="btn btn-primary" x-ng-click="submitDependent()">Save</button>
</div>
UPDATE
I changed my controller to initialize before $scope.dependent
app.controller('DependentController', function($scope, $uibModal, $uibModalInstance, $stateParams, EmployeeService){
//Following line does not work because it gets the ID of employee which is passed by querystring
//var dependentID = $stateParams.id;
$scope.dependent = { id : 0 };
if($scope.dependentid){
var currentEmployee = EmployeeService.getCurrentEmployee();
//find the current dependent
for(var i = 0; i < currentEmployee.dependents.length; i++){
//*****************************************************
//Hardcoding 1 to test the dependent number 1 but it should be the dependent id parameter
if(currentEmployee.dependents[i].id == 1){
$scope.dependent = currentEmployee.dependents[i];
break;
}
}
}
$scope.editableDependent = angular.copy($scope.dependent);
//Submit button in modal
$scope.submitDependent = function(){
DependentService.saveDependent($scope.editableDependent);
$scope.dependent = angular.copy($scope.editableDependent);
$uibModalInstance.close();
}
});
SOLVED
My button changed from this
<button x-ng-click="editDependent({{dependent.id}})">Edit</button>
To this
<button x-ng-click="editDependent(dependent.id)">Edit</button>
i think there is parsing error you have to define
$scope.dependentid = {};
before using it,
or otherwise you can use it as a model (if you are submitting a form on frontend like this)
<input type="hidden" ng-model="dependentid" />
it will be better to understand for me if you edit the code and add some frontend html
I'm trying to load data into modal using AngularJS. I did the load the data into a list of "cards" and it works fine. But, to each card, I need to open a details modal and to load the rest of the data within it. Follow my code:
//Part of index.html
<body ng-controller="CardsController">
<div class="container">
<div class="cards" ng-repeat="card in cards">
<h3>{{card.user}}</h3>
<button type="button" name="play" title="play" ng-click="toggleModal(card)">Play</button>
</div>
</div>
<my-modal show='modalShown' width='250px' height='40%'>
<h3>{{card.user}}</h3> <-- here is my problem!
</my-modal>
// js/controllers/cards-controller.js
angular.module('angstudy').controller('CardsController', function($scope, $http){
$scope.cards = [];
$http.get('http://localhost:3000/api/persons')
.success(function(retorno){
console.log(retorno);
$scope.cards = retorno;
})
.error(function(erro) {
console.log(erro);
});
$scope.modalShown = false;
$scope.toggleModal = function(card) {
$scope.modalShown = !$scope.modalShown;
};
});
// js/directives/modal-dialog.js
angular.module('modalDialog', [])
.directive('myModal', function() {
var ddo = {};
ddo.restrict = "E";
ddo.transclude = true;
ddo.scope = {
user: '#user',
show: '='
};
ddo.link = function(scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width)
scope.dialogStyle.width = attrs.width;
if (attrs.height)
scope.dialogStyle.height = attrs.height;
scope.hideModal = function() {
scope.show = false;
};
};
ddo.templateUrl = 'js/directives/modal-dialog.html';
return ddo;
});
// js/directives/modal-dialog.html (template for the directive)
<div class='ng-modal' ng-show='show'>
<div class='ng-modal-overlay' ng-click='hideModal()'></div>
<div class='ng-modal-dialog' ng-style='dialogStyle'>
<div class='ng-modal-close' ng-click='hideModal()'>X</div>
<div class='ng-modal-dialog-content'></div>
</div>
</div>
// js/main.js
angular.module('angstudy', ['modalDialog']);
The cards are been displayed normally and the modal opens, but does not display the AE values within the modal (in this case, I'm just testing the value "user", but the json has more data). If I insert just a static value, it displays...
I would've done it by keeping the modal html in a separate file and using a separate controller and I would pass the data to the Modal controller with the resolve keyword.
But since you are using the same controller on both the templates. You can keep a separate variable called $scope.SelectedCard to achieve the functionality.
In your toggleModal method you can assign the card as:
$scope.toggleModal = function(card) {
$scope.modalShown = !$scope.modalShown;
$scope.selectedCard = card;
};
and in the modal you can change to:
<my-modal show='modalShown' width='250px' height='40%'>
<h3>{{selectedCard.user}}</h3> <-- problem solved
</my-modal>
Uploading file and photo seems to be working fine on other browsers apart from FF. It seems to be its failing somewhere in the form.append but I don't get why its working on Chrome and IE but not FF.
Can someone shed a light on this one please.
controller:
$scope.uploadProfilePhoto = function() {
$timeout(function(){
var form = new FormData();
form.append("fileName", vm.profilePhoto.fileName);
form.append('file', vm.profilePhoto.file);
ProfileService.uploadProfilePicture(form)
.then(function(response){
vm.ProfilePictureUrl = api.getQualifiedUrl('image/' + response.data.ImageId);
})
});
}
Input:
<label for="profilePhoto" class="photo-upd" >
<img data-ng-src="{{vm.ProfilePictureUrl}}" id="profile-picture_image" alt="Candidate profile photo" onchange="angular.element(this).scope().uploadProfilePhoto(this)" class="img-responsive">
<span><i class="fa fa-upload"></i> Upload Photo</span>
</label>
<input id="profilePhoto" type="file" name="profilePhoto" valid-file data-oh-file fileread="vm.profilePhoto.file" filename="vm.profilePhoto.fileName" class="hidden"onchange="angular.element(this).scope().uploadProfilePhoto(this)">
Error:
vm.profilePhoto is undefined
Profile/$scope.uploadProfilePhoto/
I just notice that the vm object must be the self or this of the object/controller.
And you need to declare the vm.profilePhoto object as well:
var vm = this;
vm.profilePhoto = {};
JS:
example here:
https://jsfiddle.net/alvarojoao/v9rfn301/
var app = angular.module("turingApp", []);
app.controller("turingController", ["$scope","$timeout", function($scope,$timeout) {
var vm = this;
vm.profilePhoto = {};
$scope.uploadProfilePhoto = function() {
$timeout(function() {
var form = new FormData();
form.append("fileName", vm.profilePhoto.fileName);
form.append('file', vm.profilePhoto.file);
ProfileService.uploadProfilePicture(form)
.then(function(response) {
vm.ProfilePictureUrl = api.getQualifiedUrl('image/' + response.data.ImageId);
})
});
};
}]);
Shouldn't you be using $scope.vm In the upload function?