To display the selected pdf file in angular js while uploading - angularjs

Hi Here I have to upload single/multiple files in angular js . I have used the below link for uploading files. In this they have uploaded the images but instead I have to upload pdf and image.
<div class="container">
<div ng-controller="MyCtrl" class="row">
<button class="btn btn-primary pull-right" ng-hide="images.length == 0" ng-click="clearAll()">Clear All</button>
<h3 ng-bind="name"></h3>
<input type="file" ng-click="$event = $event" ng-model="display" multiple onchange="angular.element(this).scope().upload(event)" accept="image/png, image/jpeg, image/gif" />
<div class="row">
<div class="col-md-12"> <span ng-repeat='img in images'> <a href="#" ng-click="setImage($index)">
<img ng-src="{{img}}"
alt="Generic placeholder thumbnail" style="max-height:100px;" class="thumbnail"/>
</a>
</span>
</div>
</div>
<img ng-src="{{display}}" ng-hide="!display" />
<h4>You have upload {{images.length}} images this session.
</h4>
</div>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function ($scope) {
$scope.name = "Select Files to Upload";
$scope.images = [];
$scope.display = $scope.images[$scope.images.length - 1];
$scope.setImage = function (ix) {
$scope.display = $scope.images[ix];
}
$scope.clearAll = function () {
$scope.display = '';
$scope.images = [];
}
$scope.upload = function (obj) {
var elem = obj.target || obj.srcElement;
for (i = 0; i < elem.files.length; i++) {
var file = elem.files[i];
var reader = new FileReader();
reader.onload = function (e) {
$scope.images.push(e.target.result);
$scope.display = e.target.result;
$scope.$apply();
}
reader.readAsDataURL(file);
}
}
})
Thanks in advance.
In this I can able to see the selected images on clicking choose file. But, if it is PDF format i cant able to see the image. Pls provide the solution for PDF.

You can use javascript and PDF.JS.
Example like this:
How to Convert PDF to Image (JPEG / PNG) with Javascript using PDF.JS

Related

AngularJS toggle ng source value on click

I need some help about toggling ng-src between for example: image.jpg and image-active.jpg, but I have some issues because I need to active that with AngularJS.
This is the scenario: I called an API data from swagger and use ng-repeat to display images in html.
HTML
<div class="input-group interests-list">
<div class="checkbox" ng-repeat="interest in interests">
<label>
<div class="interest-icon">
<img src="{{interest.iconUrl}}" ng-click="changeImage()">
</div>
<input style="display: none;" type="checkbox" value="{{interest.name}}">
{{interest.name}}
</label>
</div>
</div>
Service
this.getInterests = function () {
var deferred = $q.defer();
var req = {
method: 'get',
url: 'http://customdealwebapi20180125110644.azurewebsites.net/api/Interests'
}
$http(req).then(function (response) {
deferred.resolve(response.data);
}, function (err) {
console.log(err)
});
return deferred.promise;
}
Controller
TestService.getInterests().then(function (data) {
$scope.interests = data;
});
and everything works fine
Now I want to achieve when someone click on the image, ng-src should be changed to image-active.jpg, and on the next click image should be changed to default value (image.jpg)
I know how to achieve through jQuery, like this
$(".interests-list .checkbox label input[type='checkbox']").change(function () {
var selectedIcon = $(this).val();
if (this.checked) {
console.log($(this).prev())
$(this).prev().find("img").attr("src", "assets/img/home/icons/" + selectedIcon + "-active.png");
} else {
$(this).prev().find("img").attr("src", "assets/img/home/icons/" + selectedIcon + ".png");
}
});
Thank you
You can either use ng-show
<div class="checkbox" ng-repeat="interest in interests" ng-init="interest.active = false">
<label>
<div class="interest-icon">
<img ng-show="interest.active == true" src="active.png" ng-click="interest.active = !interest.active">
<img ng-show="interest.active == false" src="other.png" ng-click="interest.active = !interest.active">
</div>
</label>
</div>
or you can pass interest to your click function and set image src in your controller
<img src="{{interest.iconUrl}}" ng-click="changeImage(interest)">
$scope.changeImage = function(interest){
if(checked)
interest.iconUrl = "active.png";
else
interest.iconUrl = "other.png";
}

AngularJS insert data to to JSON file

I have been trying and failing at this all day. I'm quite new to all this. This is a very simple angularJS learning exercise that I can't figure out.
My GET command successfully pulls the JSON data but the POST command in the addItem function is non-responsive. I believe I'm missing the server configuration but I don't know where I would put this.
There are only two files; the app and the json file (list.php); the content of both below. This app is currently running at:
http://pagemakr.com/list/L8/
THE APP - index.php:
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrlx", function($scope,$http) {
$http.get("list.php").then(function (response) {
$scope.items = response.data.items;
});
$scope.addItem = function () {
var data = { "item":$scope.itemInput }
$http.post("list.php", data).then(function (response) {
if (response.data)
$scope.msg = "Success!";
}, function (response) {
$scope.msg = "Didn't Work!";
});
}
});
</script>
<div ng-app="myShoppingList" ng-cloak ng-controller="myCtrlx" class="w3-card-2 w3-margin" style="max-width:400px;">
<header class="w3-container w3-light-grey w3-padding-16"><h3>List</h3></header>
<ul class="w3-ul">
<li ng-repeat="x in items" class="w3-padding-16">{{x.item}}<span ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">x</span></li>
</ul>
<div class="w3-container w3-light-grey w3-padding-16">
<div class="w3-row w3-margin-top">
<div class="w3-col s10">
<input placeholder="Add items here" ng-model="itemInput" class="w3-input w3-border w3-padding">
</div>
<div class="w3-col s2">
<button type="button" value="Submit" ng-click="addItem()" class="w3-btn w3-padding w3-green">Add</button>
</div>
</div>
<p class="w3-text-red">{{errortext}}</p>
</div>
</div>
THE JSON DATABASE - list.php:
{
"items":
[
{"item":"peas"},
{"item":"carrots"},
{"item":"jam"}
]
}

AngularJS 1.x: Dynamically created multiple File Upload fields

You have to excuse me, I do not use Angular that often. I need to implement a solution in which I can upload files from dynamically generated input fields.
The catch is that I cannot use any directives (this is due to the framework I am using in which AngularJS is implemented).
My current code for creating fields:
$scope.addNewFile = function() {
var newFileNo = $scope.files.length + 1;
$scope.files.push({'id': 'file' + newFileNo});
};
$scope.removeFile = function() {
var lastFile = $scope.files.length - 1;
$scope.files.splice(lastFile);
};
And here is the code for uploading files (not correct, because of static id and name values:
$scope.uploadFile = function() {
var file = document.getElementById('file').files[0],
r = new FileReader;
r.onloadend = function (e) {
var data = e.target.result;
console.log('data');
console.log(data);
// http.post
};
r.readAsArrayBuffer(file);
};
And here is my HTML:
<div data-ng-repeat="file in files">
<div class="row top-buffer">
<div class="col-lg-10">
<input type="file"
ng-model="file.name"
name="file"
class="form-control"
id="file">
</div>
<div class="col-lg-2 text-right">
<div class="btn btn-primary" ng-click="uploadFile()">Upload</div>
</div>
</div>
</div>
<div class="row top-buffer">
<div class="col-lg-11"></div>
<div class="col-lg-1 text-right">
<div class="glyphicon glyphicon-plus" aria-hidden="true" ng-click="addNewFile()"></div>
<div class="glyphicon glyphicon-minus" aria-hidden="true" ng-click="removeFile()"></div>
</div>
</div>
I can't really understand how I can get the values of dynamically generated file fields... any help appreciated!
There is no ng-model for <input type=file, but you can achieve what you want setting the id dynamically with ng-attr:
<div ng-repeat="file in files">
{{file.id}}:
<input type="file"
ng-attr-name="{{file.id}}"
ng-attr-id="{{file.id}}">
</div>
On uploadFile() you can post them:
$scope.uploadFile = function() {
$scope.files.forEach(function(file) {
// $http.post: document.getElementById(file.id).files[0])
});
};
Example on Fiddle: https://jsfiddle.net/virgilioafonsojr/92nw4j4f/1/
I hope it helps.
Writing an uploader properly is a very difficult task. A major problem with an upload component/directive is getting it to work in Internet Explorer; because it can only be used once in IE. Another problem is that IE will not let you programmatically "press" the button, it must be a real mouse click.
There are upload libraries out there for AngularJs, just google. However if you are intent on doing it yourself then you can use my git repo as an example of how it should be done. Just use the jwtUploader and jwtUploaderButton directives.
https://github.com/smylydon/SEPE-7WCM0033-0206-FRONTEND/tree/master/client/app

Images from firebase storage in ngrepeat won't show

I am trying to download images from firebase storage into an ng-repeat. The syntax i am using i got from here and also from here.
.controller('tryCtrl', function($scope,$firebaseStorage,$firebaseArray){
$scope.user = 'OPD0wmF3syajsD94ANBBEQgzWPz2';
const rootRef = firebase.database().ref();
const ref = rootRef.child('UserData' + '/' + $scope.user);
var list = $firebaseArray(ref);
$scope.listOFProducts = list;
$scope.getImageUrl = function(Image){
var storageRef = firebase.storage().ref($rootScope.user + '/' + Image);
var storage = $firebaseStorage(storageRef);
return storage.$getDownloadURL().then(function(url) {
$scope.url = url;
console.log($scope.url);
return url;
})
};
})
Here is my html
<div class="col-xs-6 col-sm-4 col-md-3 col-lg-3" ng-repeat="items in details.Products">
<div class="spacer" ng-init=""></div>
<a class="button" data-toggle="modal" data-target="#myModal" ng-click="open(items)">
<img ng-src="{{getImageUrl(items.Image)}}" class="img-responsive">
</a>
<p>{{items.Price}}</p>
</div>
<img ng-src="{{url}}">
My challenge is that the returned url does not display any image. The url attached to scope however displays all the image; changing from one image to another within about a second of each image. Conosole.log($scope.url) shows the download url constantly changing. I will be grateful if someone can help me figure this out.
You could directly bind the url, since you have the image in the scope variable,
<img ng-src="url" class="img-responsive">

Unable to upload the image in protractor

Facing following error:
Failed: No element found using locator: By(css selector, input[type="images"])
Protractor code:
it("image upload",function(){
browser.ignoreSynchronization = true;
browser.sleep(4000);
element( by.css('[ng-click="imagePost()"]') ).click();
browser.sleep(3000);
var ele = element(by.model("files")).click();
browser.wait(EC.visibilityOf(ele),8000,'Ele is not presented');
var fileToUpload = "C:\Users\Shiva\Desktop\mdkg.jpg;"
console.log(fileToUpload);
var absolutePath = path.resolve(fileToUpload);
console.log(absolutePath);
$('input[type="images"]').sendKeys(absolutePath);
element(by.buttonText('Post Image')).click();
browser.sleep(5000);
});
HTML code to upload image:
<div ngf-drop ng-model="files" ngf-pattern="image/*" data-ngf-multiple="true" ng-repeat="image in images1" ngf-size>
<img src="{{image}}" width = "100%" height = "100%" class="m-l img-responsive img-rounded m-b" alt="post images">
</img-crop>
<span ng-show="loading" class="text-center col-xs-12" ></span>
</div>
</div>
<div class="modal-actions ">
<button type="submit " class="btn-link modal-action ">
<strong><span class="icon icon-user "></span>postImg</strong>
</button>
<button type="button" id="fileinput" ng-model="files" ngf-select accept="image/* " data-ngf-multiple="true" class="btn-link modal-action">Upload Image
Here I am uploding image, when I click on upload image it navigates to local system and it should upload the image. And after uploading it should post.
here is my answer using page objects:
this.uploadImage = function(){
var path = require('path');
var remote = require('../../../../node_modules/protractor/node_modules/selenium-webdriver/remote');
browser.setFileDetector(new remote.FileDetector());
var fileToUpload = '../../mdkg.jpg';
var absolutePath = path.resolve(__dirname, fileToUpload);
var fileElem = element(by.css('input[type="file"]'));
// Unhide file input
browser.executeScript("arguments[0].style.visibility = 'visible'; arguments[0].style.height = '1px'; arguments[0].style.width = '1px'; arguments[0].style.opacity = 1", fileElem.getWebElement());
fileElem.sendKeys(absolutePath);
// take a breath
browser.sleep(4000);
element(by.buttonText('Post Image')).click();
browser.sleep(4000);
};
post_text.uploadImage();

Resources