I am trying to upload a file through Angularjs. I am hitting the service but not able to get the file on the server. I have posted my code below. Please let me know the errors/modifications in the code.
<html>
<head>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<form name="demo">
<input type = "file" file-model = "myFile"/>
<button type="submit" ng-click = "uploadFile()">upload me</button>
</form>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
console.log('file uploaded');
})
.error(function(){
console.log('file not uploaded');
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "http://172.29.5.86:8080/marketplace/inventory/testImageUpload.service";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
I can recommend you to use https://github.com/flowjs/ng-flow.
HTML
<div flow-init
flow-name="flowObject.flow" <!-- optional -->
flow-file-added="fileAdded($file)"> <!-- optional -->
<!-- Your HTML -->
<span class="btn btn-default" data-flow-btn>Select Files</span>
<span class="btn btn-primary" ng-click="uploadFiles()">Upload</span>
</div>
Controller
$scope.flowObject = {};
$scope.uploadFiles = function () {
$scope.files = $scope.flowObject.flow.files;
// some logic
myService.uploadFilesSomewhere($scope.files).then(function (response) {
// some other logic
});
};
$scope.fileAdded = function (file) {
// some logic
};
Related
Here is my html code:
<div ng-app="myApp" ng-controller="customersCtrl">
<p id="druzyny"></p>
</div>
and then in angular script:
var app = angular.module('myApp', []);
document.getElementById("search1").onclick = app.controller('customersCtrl', function($scope, $http){
var place = document.getElementById("place").value;
var sel1 = document.getElementById("sel1").value;
var sel2 = document.getElementById("sel2").value;
var req = {
method: 'post',
url: 'findTournament',
headers: {
'Content-type': 'application/json'
},
data: {place: 'test'}
};
$http(req).then(function(response){
});
});
I`ve got button id="search1" and i want that angular execute only when i click this button, no automatically when page is reload, is it possible?
Thanks for answears
HTML:
<div ng-app="myApp" ng-controller="customersCtrl as customers">
<input data-ng-model="customers.place">
<input data-ng-model="customers.sel1">
<input data-ng-model="customers.sel2">
<button data-ng-click="customers.init()"></button>
</div>
JS:
angular.module('myApp', []);
angular
.module('myApp')
.controller('customersCtrl', function($scope, customersService){
var vm = this;
vm.init = function(){
customersService.findTournament({place: vm.place, sel1: vm.sel1, sel2: vm.sel2})
.then(function(res){});
};
});
angular
.module('myApp')
.service('customersService', function($http){
return {
findTournament: findTournament
};
function findTournament(data){
return $http.post('findTournament', data);
}
});
I have a services.js file where I placed my facotry:
.factory('dataShare',function($rootScope){
var service = {};
service.data = false;
service.sendData = function(data){
this.data = data;
$rootScope.$broadcast('data_shared');
};
service.getData = function(){
return this.data;
console.log('this.data')
};
return service;
})
And my controllers, in the controller.js file look like this:
.controller('recommendedJobsCtrl', function($q,$scope, $ionicSideMenuDelegate,$window,$http,dataShare) {
$scope.text='hey';
$scope.post=function(){
dataShare.sendData($scope.text);
console.log('here')
}
})
.controller('jobPostCtrl', function($scope,$ionicSideMenuDelegate,dataShare) {
$scope.text = '';
$scope.$on('data_shared',function(){
var text = dataShare.getData();
$scope.text = text;
console.log(text)
});
})
When I did console.log, i realized that the service.getData isn't wokring, i.e the receiving controller (jobPostCtrl) isn't getting anything.
How can i fix this?
Here is example that works.
<!doctype html>
<html>
<head>
<title>AngularJS</title>
<script src="angular.min.js"></script>
<script type="text/javascript">
var sampleApp = angular.module('sampleApp', []);
sampleApp.factory('dataShare',function($rootScope){
var service = {};
service.data = false;
service.sendData = function(data){
this.data = data;
$rootScope.$broadcast('data_shared');
};
service.getData = function(){
return this.data;
console.log('this.data')
};
return service;
});
sampleApp.controller('recommendedJobsCtrl', function($q,$scope,$window,$http,dataShare) {
$scope.text='hello world!';
$scope.post=function(){
dataShare.sendData($scope.text);
console.log('sent: ' + $scope.text);
}
});
sampleApp.controller('jobPostCtrl', function($scope,dataShare) {
$scope.text = '';
$scope.$on('data_shared',function(){
var text = dataShare.getData();
$scope.text = text;
console.log('received: ' + $scope.text);
});
});
</script>
</head>
<body ng-app="sampleApp">
<div ng-controller="recommendedJobsCtrl">
<input type="text" ng-model="text" />
<button ng-click="post()">Send</button>
</div>
<div ng-controller="jobPostCtrl">
<p>{{text}}</p>
</div>
</body>
</html>
Use
$rootScope.$broadcast('data_shared',this.data);
and $scope.$on('data_shared',function(event,data){
$scope.$scope.text=data;
});
Hello everyone I am really new to developing with AngularJS and I am trying to figure out how to use BLOB to download a PDF locally to a machine. I already got it to work with a JSON and now I need a PDF. I have written some code but it doesn't seem to be working.
html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.center {
position: absolute;
left: 50%;
bottom: 50%;
}
.btn-purple {
background-color: rgb(97, 34, 115);
width: 100px;
}
</style>
<meta charset="UTF-8">
<title></title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="center" ng-controller="jsonController" ng-app="app">
<a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
<button type="button" class="btn btn-purple">{{fileName}}</button>
</a>
</div>
<div class="center" ng-controller="pdfController" ng-app="app">
<a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
<button type="button" class="btn btn-purple">{{fileName}}</button>
</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript-canvas-to-blob/3.1.0/js/canvas-to-blob.js"></script>
<script src="app.js"></script>
</body>
</html>
controller.js
var app = angular.module('app', []);
app.config(['$compileProvider', function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
}]);
app.controller('jsonController', function ($scope, $window, $http, $log) {
$http.get('data.json')
.success(function (info) {
var data = angular.toJson(info, true);
data = data.replace(/\n/g, "\r\n")
console.log(data)
var blob = new Blob([data], {type: "octet/stream"}),
url = $window.URL || $window.webkitURL;
$scope.fileUrl = url.createObjectURL(blob);
$scope.schemaName = "test"
$scope.fileName = $scope.schemaName + ".json"
})
});
app.controller("pdfController", function ($scope, $http, $log, $sce) {
$http.get('data.json' + $stateParams.id,
{responseType: 'arraybuffer'})
.success(function (response) {
var file = new Blob([(response)], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
});
Possible Try-
HTML:
<button ng-click="downloadPdf()" >Download PDF</button>
JS controller:
'use strict';
var app = angular.module('app')
.controller('ctrl', function ($scope, MathServicePDF) {
$scope.downloadPdf = function () {
var fileName = "file_name.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
ServicePDF.downloadPdf().then(function (result) {
var file = new Blob([result.data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
};
});
JS services:
app.factory('ServicePDF', function ($http) {
return {
downloadPdf: function () {
return $http.get('api/my-pdf', { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
};
});
Happy Helping!
Tested with large files (> 1.5 GB) on
Firefox 56.0
Safari 11.0
Use the following in your angular controller:
$scope.download = function() {
$http({
method: 'GET',
url: fileResourceUrl,
responseType: 'blob'
}).then(function(response) {
var blob = response.data;
startBlobDownload(blob, "largedoc.pdf")
});
};
function startBlobDownload(dataBlob, suggestedFileName) {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
// for IE
window.navigator.msSaveOrOpenBlob(dataBlob, suggestedFileName);
} else {
// for Non-IE (chrome, firefox etc.)
var urlObject = URL.createObjectURL(dataBlob);
var downloadLink = angular.element('<a>Download</a>');
downloadLink.css('display','none');
downloadLink.attr('href', urlObject);
downloadLink.attr('download', suggestedFileName);
angular.element(document.body).append(downloadLink);
downloadLink[0].click();
// cleanup
downloadLink.remove();
URL.revokeObjectURL(urlObject);
}
}
Change your responseType from responseType: 'arraybuffer'
to responseType: 'blob'
In you controller PHP
return $pdf->stream();
In you controller AngularJS
$http.post('generate', {
dateStart: $scope.ds,
dateEnd: $scope.de
},
{
responseType: 'arraybuffer'
}).then(function success(response) {
var blob = new Blob([response.data], { type: "application/pdf"});
saveAs(blob, "filename.pdf");
}, function error(error) {
$scope.recordErrors(error);
});
This code worked for me in angular 9, Yii2, while using mpdf
this._gService.download_post(`controller/action`, postData).pipe(takeUntil(this._unsubscribeAll)).subscribe(result => {
const fileURL = URL.createObjectURL(result);
// Direct print preview
// const iframe = document.createElement('iframe');
// iframe.style.display = 'none';
// iframe.src = fileURL;
// document.body.appendChild(iframe);
// iframe.contentWindow.print();
// Direct Download
const fileName = 'Patient Report';
const a = document.createElement('a');
document.body.appendChild(a);
a.href = fileURL;
a.download = fileName;
a.click();
}, error => {
// show error message
});
What I want to do is pretty simple. I have two forms. One form is visible in the beginning and once that form is submitted it dissappears and the second form appears. I am trying to use a flag variable set at $rootscope.showFlag but it doesn't seem to work.
Here is my HTML part:
<div ng-app="myapp" >
<div class="container" ng-controller="addItemController" ng-show="showFlag">
<form class="form-signin">
<h2 class="form-signin-heading">Add an item</h2>
<input type="text" name="itemName" ng-model="myForm.itemName" id="inputItemName" class="form-control" placeholder="Name of the item" autofocus required>
<button class="btn btn-lg btn-primary btn-block" ng-click="myForm.submitTheForm()">Add item</button>
</form>
</div> <!-- /container -->
<div class="container" ng-controller="MyCtrl" ng-show="!showFlag">
<input type="text" ng-model="username"></br></br>
<button class="btn btn-lg btn-primary btn-block" ngf-select ng-model="files">Select file</button>
</div>
</div>
And this is my Angular app:
var app = angular.module("myapp", ['ngFileUpload'])
.run(function($rootScope) {
$rootScope.showFlag = true;
});
app.controller("addItemController", function($rootScope, $scope, $http) {
$scope.myForm = {};
$scope.showFlag = true;
Data.Show = 10;
$scope.myForm.submitTheForm = function(item, event)
{
console.log("--> Submitting form");
var dataObject = {
itemName : $scope.myForm.itemName,
};
var responsePromise = $http.post("/angularjs-post", dataObject, {});
responsePromise.success(function(dataFromServer, status, headers, config) {
console.log(dataFromServer.title);
//alert("Submitting form OK!");
$rootScope.showFlag = false;
});
responsePromise.error(function(data, status, headers, config) {
alert("Submitting form failed!");
});
}
$scope.myForm.uploadPhoto = function(item, event)
{
console.log('Uploading photo');
}
});
app.controller('MyCtrl', ['$scope', 'Upload', function ($rootScope, $scope, Upload) {
$scope.$watch('files', function () {
$scope.upload($scope.files);
});
$scope.log = '';
$scope.upload = function (files) {
if (files && files.length) {
var file = files[0];
Upload.upload({
url: '/upload',
fields: {
'username': $scope.username
},
file: file
}).progress(function (evt) {
// during progress
}).success(function (data, status, headers, config) {
// after finishing
});
}
};
}]);
You set showFlag to true in two places.
In the root scope.
.run(function($rootScope) {
$rootScope.showFlag = true;
});
And in the local scope.
app.controller("addItemController", function($rootScope, $scope, $http) {
$scope.myForm = {};
$scope.showFlag = true;
As the ng-show for the first form looks in the local scope first it won't be affected even when you set the rootScope flag to false.
One possible reason could be that you have misspelled the controller name
it should be addSellItemController.
<div class="container" ng-controller="addSellItemController" ng-show="showFlag">
Another small mistake is you have not added $rootScope as a dependency in your MyCtrl directive.
app.controller('MyCtrl', ['$rootScope','$scope', 'Upload', function ($rootScope, $scope, Upload) {
...
});
I want to have a button on my page from where I can upload an image from local system and then I want to save that image in my local storage.
I am keen to learn angularjs here.
You'd want to encode the image as a base 64 string and store that in local storage.
See this answer for an example of how to convert the image to a base 64 string. toDataURL() returns a string, which you can then store the same way you would normally store a string in a JSON object.
To display the image, you use something like this:
<img src="data:image/jpeg;base64,blahblahblah"></img>
where blahblahblah is the string returned.
Follow below code for upload and save image using AngularJS
Create index.php file and initialize app and create AngularJS controller.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<div>
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</div>
</body>
</html>
After this, Create app.js and write code to upload image using AngularJS.
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
var uploadUrl = "post.php";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
After this, Create post.php file to upload file into storage.
<?php $upload_dir = "images/";
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png", "gif");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg")) && in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0){
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
if (file_exists($upload_dir.$_FILES["file"]["name"])) {
echo 'File already exist';
} else {
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$filename = rand().$_FILES['file']['name'];
$targetPath = $upload_dir.$filename; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo 'success';
}
}
}
} ?>
Create images folder.
Hope this will help you. For reference: http://jsfiddle.net/JeJenny/ZG9re/