net::ERR_INVALID_URL when setting <img> src from $http.get result - angularjs

I have a angular directive that works on img tags and loads the image dynamically as a base64 string. I use $http.get to load the image and set it into the img.src like this:
var onSuccess = function(response) {
var data = response.data;
element.attr("src", "data:image/png;base64," + data);
};
var onError = function(response) {
console.log("failed to load image");
};
scope.$watch('authSrc', function(newValue) {
if (newValue) {
$http({
method: "GET",
url: scope.authSrc,
data: ""
}).then(onSuccess, onError)
}
});
after i set the src attribute, i get the net::ERR_INVALID_URL error.
The string that returns from the request looks like this:
IHDR����^tiDOT#(##AMȯz�#IDATx��uw\�ٷ�o����G�B["...
Any ideas?
thanks

Got it to work will the help of This link.
Trick was to use responseType: "blob", and use URL/webkitURL createObjectURL()
Here's the full directive:
'use strict';
app.directive('authSrc',function ($http) {
return {
restrict: 'A',
scope: {
authSrc: "="
},
link: function (scope, element) {
var onSuccess = function(response) {
var data = response.data;
var url = window.URL || window.webkitURL;
var src = url.createObjectURL(data);
element.attr("src", src);
};
var onError = function(response) {
console.log("failed to load image");
};
scope.$watch('authSrc', function(newValue) {
if (newValue) {
$http({
method: "GET",
url: scope.authSrc,
responseType: "blob"
}).then(onSuccess, onError)
}
});
}
}
});

Specify the responseType in your request, and you may have to disable default transforms that $http attempts on the data.
see here

My problem was specifying a zoom level after the base64 string '#zoom=90'

Related

Angularjs $http then is not working properly

I get a value of "True" in my response. How come my debugger and alert and AccessGranted() in the .then of my $http is not being invoked. Below is my Script:
app.controller("LoginController", function($scope, $http) {
$scope.btnText = "Enter";
$scope.message = "";
$scope.login = function() {
$scope.btnText = "Please wait...";
$scope.message = "We're logging you in.";
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
}).then(function (response) {
debugger;
alert(response.data);
if (response.data == "True") {
AccessGranted();
} else {
$scope.message = response.data;
$scope.btnText = "Enter";
}
},
function (error) {
$scope.message = 'Sending error: ' + error;
});
}
$scope.AccessGranted = function() {
window.location.pathname("/Home/HomeIndex");
}
});
This is in my HomeController
public ActionResult HomeIndex()
{
var am = new AuditManager();
var auditModel = new AuditModel()
{
AccountId = 0,
ActionDateTime = DateTime.Now,
ActionName = "Home",
ActionResult = "Redirected to Home"
};
am.InsertAudit(auditModel);
return View("Index");
}
Please see image for the response I get.
seems like your approach is wrong
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Try this,
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
})
.then(function (response) {
console.log(response);
},
function (error) {
console.log(error);
});
And check your browser console for logs or any errors
Make sure the response is application/json content type, and content is json.
You can also write own httpProvider for check result from server
module.config(['$httpProvider', function ($httpProvider) {
...
I would suggest you to code like this instead of then so whenever there is success, The success part will be invoked.
$http.get('/path/').success(function (data) {
$scope.yourdata = data.data;
//console.log($scope.yourdata);
}).error(function (error){
//error part
});

Using $resource to upload file

I have gone through all the questions on this website on this topic and pretty much tried all codes. Following is the latest snippet that I have borrowed from the answers listed on this website. I am trying to upload a file asynchronously to AWS s3 endpoint. I get my signed url correctly but am unable to actually upload the file.
HTML:
<form name="Details" ng-controller="DetailsController">
<input type="file" file-input="files" />
<button ng-click="initUpload()">Upload</button>
</form>
fileInput Directive and DetailsController:
module.directive('fileInput', ['$parse', function ($parse) {
return {
restrict: 'A',
link:function(scope, elm, attrs){
elm.bind('change', function(){
$parse(attrs.fileInput)
.assign(scope, elm[0].files);
scope.$apply();
});
}
}
}]).controller("DetailsController", ["$scope", "PostalService",
function ($scope, PostalService) {
getSignedURLForUpload = function(userId, filename, filetype){
return (PostalService.getSignedURLForUpload(userId, filename, filetype));
};
$scope.initUpload = function(){
var signedUrl = getSignedURLForUpload($scope.userId, $scope.files[0].name,$scope.files[0].type);
signedUrl.then(function (data) {
var uploadPromise = PostalService.uploadFile($scope.files, data.signedRequest);
uploadPromise.then(function(result) {
$scope.awsurl = data.url;
});
});
};
]);
PostalService:
module.factory("PostalService",
["$resource",
function($resource) {
var functions = {
getSignedURLForUpload: function(userId, filename, filetype) {
var SignUrl = $resource("host end point?userid="+userId+"&file-name="+filename+"&file-type="+filetype);
var promise = SignUrl.get().$promise;
return promise;
},
uploadFile: function(file, signedRequest) {
var Upload = $resource(signedRequest, null, {
'save':{
method: 'POST',
transformRequest: function(data){
var fd = new FormData();
angular.forEach(data, function(value, key) {
if(value instanceof FileList) {
if(value.length ===1){
fd.append(key, value[0]);
}else {
angular.forEach(value, function(file, index){
fd.append(key+'_'+index, file);
});
}
}else {
fd.append(key, value);
}
});
return fd;
},
headers: {'Content-Type' : undefined}
}
});
var promise = Upload.save(file).$promise;
return promise;
}
};
return functions;
}
]);
So the issue was in implementation of uploadFile function of PostalService.
The headers needed to be set properly:
1. 'Content-Type' : 'image/jpeg'
2. Authorization: 'undefined'
Authorization headers were being automatically set by my application and in this case, I had to nullify them as the particular url link used to upload the file to the server was pre-signed and signature was part of the query.
Content type needed to be 'image/jpeg' and not undefined as that was expected by my backend server.
Finally, the method 'POST' didn't work. Had to replace it with 'PUT' instead.

sending files via POST with AngularJS

I have a problem sending data via POST in angular,
my data include 2 files and some text field,
the problem is that the service doesn't receives any data.
this is my code:
var inputs = document.querySelectorAll( 'input[type="file"]' );
Array.prototype.forEach.call( inputs, function( input ){
input.addEventListener( 'change', function( e ){
if(this.id == "zipToUpload")
$scope.zipToUpload = this.files[0];
else
$scope.imgToUpload = this.files[1];
});
});
$scope.submit = function(){
var getInput = {nome: $scope.app_name, zipToUpload: $scope.zipToUpload, imgToUpload: $scope.imgToUpload, url: $scope.app_url,
secure: $scope.checkbox_pass, hide: $scope.checkbox_hide, beta: $scope.checkbox_beta, password: $scope.app_pass, location: "1" };
var req = {
method: 'POST',
url: 'api/rest/app/insert_app.php',
headers: {
'Content-Type': undefined
},
data: getInput
}
$http(req)
.then(function(result) {
console.log(result);
});
}
You can not directly upload file using model in angular. First you need a directive to bind files to the model.
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]);
});
});
}
};
}]);
And the input will be like :
<input type = "file" file-model = "myFile"/>
And the you can send post request using form data
$scope.upload = funtion(){
var fd = new FormData();
fd.append('file', $scope.myFile);
var req = {
method: 'POST',
url: 'api/rest/app/insert_app.php',
headers: {
'Content-Type': undefined
},
data: fd
}
$http(req)
.then(function(result) {
console.log(result);
});
}

How to make a loading (spin) while requesting to server by $http on angularJS

$http({
method: 'POST',
url: '',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
if(response.data == 'true'){
swal("Good job!", "New case has been created", "success");
}
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I want to show a progress bar or spin on bootstrap while http request on angularjs
Sugessting you to use this angular-loading-bar
Steps
Include the script references and css as mentioned in the above
github, you can use cdn as well as mentioned.
Add these two functions in your controller
$scope.start = function() {
cfpLoadingBar.start();
};
$scope.complete = function () {
cfpLoadingBar.complete();
}
Include the 'angular-loading-bar', 'ngAnimate' as dependencies.
Add the below code for the app configurations
If you are looking for the progress bar
app.config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
cfpLoadingBarProvider.includeSpinner = false;
}])
If you are looking for a spinner
app.config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
cfpLoadingBarProvider.includeSpinner = true;
}])
Finally, In your $http request call the $scope.start() function and in your success method call the $scope.complete()
LIVE DEMO
A simple way:
html:
<div class="spinner" ng-show="loading"></div>
js :
$scope.loading = true
$http.post(...).then(function(response){
$scope.data = response.data // or whatever you needs...
$scope.loading = false
},function(){
$scope.loading = false
console.log("error")
})
If you want to generalize, you can also have a look to http interceptor : https://docs.angularjs.org/api/ng/service/$http#interceptors

How to delete file in dropzone?

init: function() {
dzClosure = this;
document.getElementById("place-order").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("key", $scope.formData.order_id);
});
this.on('success', function(file, resp) {
console.log(resp); //result - {error:false, file_id:10}
file_ids.push(resp.file_id);
});
},
removedfile: function(file) {
console.log(file_ids);
x = confirm('Do you want to delete?');
if (!x) return false;
var name = file.name;
$.ajax({
type: 'POST',
url: 'orders/fileDelete.php',
data: {"file_id": file_ids},
dataType: 'json'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
Above my code working fine. But I want to delete my mysql row while clicking on the "Remove" button in dropzone. I am unable to get the current file_id in my removedfile function. Please help me and let me know how I will get resp.file_id in my removedfile function?
You could set an id property to file on success event, then on removal just get it as file.id. Hope this helps you.
init: function() {
dzClosure = this;
document.getElementById("place-order").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("key", $scope.formData.order_id);
});
this.on('success', function(file, resp) {
file.id = resp.file_id;
});
},
removedfile: function(file) {
x = confirm('Do you want to delete?');
if (!x) return false;
//send delete to backend only if file was uploaded.
//Dropzone will cancel requests in progress itself.
if(file.id) {
$.ajax({
type: 'POST',
url: 'orders/fileDelete.php',
data: {"file_id": file.id},
dataType: 'json'
});
}
}
After lots of research I found where was error in my code.
Actually my ajax responded JSON. But here is dropzone.js not getting json data. So I have converted my dynamic String data to JSON format.
Code:
this.on('success', function(file, resp) {
console.log(resp); // result - {error:false, file_id:10}
var response = JSON.parse(resp);
file.file_id = response.file_id;
});

Resources