Error 403 when I tried upload file(image) to server - javascript

I want create server for uploading images and filling json via form. I have tried many codes and plugins for downloading to server, but I have always get 403 error. What is my mistake. I have used only jQuery or AngularJs without backend. This is a link: http://salegid.com/dist/ The last one variant:
HTML
<div ng-app="myApp">
<div ng-controller="MyController">
<input type="file" fileread="uploadme" />
<img src="{{uploadme}}" width="100" height="50" alt="Image preview...">
<br/>
<p>
Image dataURI:
<pre>{{uploadme}}</pre>
</p>
<br/>
<button ng-click="uploadImage()">upload image</button>
</div>
</div>
JS
var app = angular.module('myApp', [
'ngResource',
'ngRoute'
])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'index.html',
controller: 'MyController',
})
.otherwise({
redirectTo: '/'
});
}])
.controller('MyController', ['$scope', '$http', function($scope, $http) {
//the image
$scope.uploadme;
$scope.uploadImage = function() {
var fd = new FormData();
var imgBlob = dataURItoBlob($scope.uploadme);
fd.append('file', imgBlob);
$http.post(
'imageURL',
fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}
)
.success(function(response) {
console.log('success', response);
})
.error(function(response) {
console.log('error', response);
});
};
//you need this function to convert the dataURI
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {
type: mimeString
});
};
}])
.directive('fileread', [
function() {
return {
scope: {
fileread: '='
},
link: function(scope, element, attributes) {
element.bind('change', function(changeEvent) {
var reader = new FileReader();
reader.onload = function(loadEvent) {
scope.$apply(function() {
scope.fileread = loadEvent.target.result;
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}
]);
Can you help me because I'm stuck. Thanks a lot.

403 means Forbidden request. This means that the server hasn't gotten all of the authentication credentials it needs from your request. Please check with your backend and see what headers are required.
403 FORBIDDEN
The server understood the request but refuses to authorize it.
A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT automatically repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.
An origin server that wishes to "hide" the current existence of a forbidden target resource MAY instead respond with a status code of 404 Not Found.
I see from your code that you're not setting any authentication headers. In AngularJS, app level auth headers can be set using:
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = /* ... */;
}])

Related

http post with formdata and other field control not going to java

I am new to AngularJs. I am trying to upload a image file (.bmp,.jpg, etc) along with its label through Jax-RS post rest API but my control in not going into java post api from my angularjs controller.
While debugging the control is not coming into java file. Could you please help to understand what si wrong in my code.
myfile.html
Label of File: <input type="text" name="iconlabel" data-ng-model="imporLabelName"><br>
Import a File: <input type="file" id="myFile" name="myfile" data-file-model="myfile"><br>
<button type="button" class="btn btn-primary pull-right" data-ng-click="uploadfile();">Submit
</button>
myFileController
define([ '{angular}/angular' ], function(angular) {
var module = angular.module('myFile', [ 'ngResource', 'colorpicker-dr' ]);
module.controller('myFileController', [ '$scope', '$sce', '$http', '$location', '$window', 'w20MessageService'
,function($scope, $sce, $http, $location, $window, w20MessageService) {
var config = {
headers: {
"Content-Type": undefined,
}
};
/*** Modale for MyFile **/
$scope.openMyFile = function() {
$("#myfile").modal("show");
};
$scope.uploadfile = function() {
$scope.file = document.getElementById('myFile').files[0];
alert('LabelName = '+$scope.imporLabelName);
var formData = new $window.FormData();
formData.append("label", $scope.imporLabelName);
formData.append("file", $scope.file);
alert('File = '+$scope.file);
var url = "uploadfile/label="+$scope.imporLabelName;
alert("URL = "+url);
$http.post(url,$scope.formData,config).success(function(response) {
$scope.result = "SUCCESS";
}).error(function(response, status) {
if (status === 400) {
w20MessageService.addMessageErreur(data.message, "msgGererParam");
} else {
w20MessageService.addMessageErreur("eox.message.error.load.traitement", "msgGererParam");
}
});
$("#myfile").modal("hide");
};
} ]);
return {
angularModules : [ 'digitalJes' ]
};
});
java api code
#POST
#Path("/uploadfile/{label}")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_PLAIN)
public Response uploadFile(#PathParam("label") String label, #FormDataParam("file") InputStream fileInputStream,
#FormDataParam("file") FormDataContentDisposition fileInputDetails) {
CacheControl cc = new CacheControl();
cc.setNoCache(true);
return Response.ok(uploadFileUtil.uploadFile(label, fileInputStream, fileInputDetails)).cacheControl(cc).build();
}
Error Code and Error Message
HTTP Status 400 – Bad Request
The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
#FormDataParam("file") InputStream fileInputStream,
#FormDataParam("file") FormDataContentDisposition fileInputDetails
Seems both of the fileInputStream and fileInputDetails variables are initializing from file parameter. Also in html the field is
...
Import a File: <input type="file" id="myFile" name="myfile" data-file-model="myfile"><br>
Here id="myFile" and name="myfile" and you are receiving those as "#FormDataParam("file")".

Google oauth2 get id_token

I am working in client side angularjs.I am try to implement google oauth2. I am getting accesstoken but i need to get id_token.
I added app.js , controller.js and html part.
I followed this tutorial: http://anandsekar.github.io/oauth2-with-angularjs/
app.js:
angular
.module('angularoauthexampleApp', [ ])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/access_token=:accessToken', {
template: '',
controller: function ($location,$rootScope) {
var hash = $location.path().substr(1);
var splitted = hash.split('&');
var params = {};
for (var i = 0; i < splitted.length; i++) {
var param = splitted[i].split('=');
var key = param[0];
var value = param[1];
params[key] = value;
$rootScope.accesstoken=params;
}
$location.path("/about");
}
})
.otherwise({
redirectTo: '/'
});
});
controller.js
angular.module('angularoauthexampleApp')
.controller('MainCtrl', function ($scope) {
$scope.login=function() {
var client_id="your client_id";
var scope="email";
var redirect_uri="http://localhost:9000";
var response_type="token";
var url="https://accounts.google.com/o/oauth2/auth?scope="+scope+"&client_id="+client_id+"&redirect_uri="+redirect_uri+
"&response_type="+response_type;
window.location.replace(url);
};
});
html:
<button class="btn btn-primary" ng-click="login()">Login</button>
You need to use nonce. Add it and id_token will be in response.
For example:
let params = {
'client_id': GOOGLE_API_CLIEND_ID,
'redirect_uri': `${location.origin}/auth/google`,
'response_type': 'id_token token',
'scope': GOOGLE_API_SCOPES,
'state': 'af0ifjsldkj',
'nonce': 'n-0S6_WzA2Mj'
};
For implicit flow nonce param is required. For more information you can check http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthRequest
To receive an id_token, you need to change your response_type param to:
var response_type="id_token";
as the response you will get an id_token. If you need both - the id_token and access_token, you should add "token" to response_type:
var response_type="token id_token";
To learn more, read OpenId article
Also you could test auth flow using Google Ouath Playground
To trigger an OpenID Connect flow, which is an extension of OAuth 2.0, you need to add the "openid" scope in the authentication request (and urlencode the space in between), so:
var scope="openid%20email";

Dynamic domain URL Rest factory AngularJS

I want change dynamic REST URL (for example if is stage or production) with a simple change in a server, but the URL don't change:
I have tried this:
.factory('Auth', ['$resource', 'Config', function($resource, Config) {
var URL = function(){
var random = Math.floor((Math.random() * 100) + 1);
window.localStorage.setItem("REST", "http://dynamic"+random+".com/");
return window.localStorage.getItem("REST");
}
return $resource(_url, {url:"url"}, {
login: { method:'POST', url: URL()},
})
}])
And this
// Generate random URL in the controller
.factory('Auth', ['$resource', 'Config', function($resource, Config) {
var URL = window.localStorage.getItem("REST");
return $resource(_url, {url:"url"}, {
login: { method:'POST', url: URL},
})
}])
But when I change the url ( I check this url in local storage and its change) the domain is the same anywhere unless that I reload the page, in this case works.
Thanks
You can do something like that:
Add a 2 new constant:
.constant('HOST_CDN', {
development: {
api: 'http://YOUR_LOCAL_DOMAIN',
},
production: {
api: 'http://YOUR_PRODUCTION_DOMAIN',
}
})
.constant('ENV', 'development')
Create new service:
var domain = null;
(function getDomains() {
domain = HOST_CDN[ENV];
if (!domain) {
throw 'Could not get domains';
}
domain.api = domain.api.concat('/')
.replace(/\/\/$/, '/');
})();
return {
api : domain.api
};

Angular.js request/response Node.js

I am trying to request some data from node.js server from my angular.js. The problem is that upon data response i see a blank browser window with my json object printed on it. I want angular.js to recognize the response and stay on page.
HTML form - template that gets loaded with loginController
<section class="small-container">
<div class="login-form">
<form action="/login" method="post" ng-submit="processForm()">
<input ng-model="formData.username" type="text" name="username">
<input ng-model="formData.password" type="password" name="password">
<button>login</button>
</form>
</div>
</section>
Angular.JS
var app = angular.module("blavor", ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "/index",
controller: "loginController"
})
.when("/register", {
templateUrl: "/register",
controller: "registerController"
})
.otherwise("/");
$locationProvider.html5Mode(true);
}]);
app.controller('loginController', function($scope, $http) {
$scope.formData = {};
$scope.processForm = function() {
$http({
method: 'POST',
url: '/login',
data: $.param($scope.formData),
processData: false,
responseType: "json",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
console.log(data);
if (!data.success) {
alert("Noo!");
} else {
alert("YEEEY!");
}
});
};
});
Node.js Server - index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require('express');
var bodyParser = require('body-parser');
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded({ extended: false }) );
var routes = require('./routes')(app);
http.listen(3000, function() {
console.log('listening on *:3000');
});
module.exports.start = start;
Node.js Server - routes
module.exports = function(app) {
app.post('/login', function(request, response) {
console.log(request.body);
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify({value:"somevalue"}));
});
}
I am using AngularJS v1.2.24 and Node.js v0.10.25
console.log(data) in angular never gets called..
Hi try removing the action and method from your form.
From the ng-submit docs
Enables binding angular expressions to onsubmit events.
Additionally it prevents the default action (which for form means sending the request to the server and reloading the current page), but only if the form does not contain action, data-action, or x-action attributes.
So by adding those, you are causing the page to refresh when the form is submitted.
Without them, angular will call $event.preventDefault() for you, which stops the page from being reloaded.
EDIT: Just to add, you were seeing the correct data from the server because you're responding with preset data, which will always be provided when someone posts to /login.
So your form is currently circumventing angular entirely, and directly getting the data from the server.

Angularjs: use ".then" and get response

I want send a http request and get response of this request. I want if data is save, I get database information and if doesn't save, I get errors. For this, I want use .then in angularjs. I create angularjs controller and services to do this. I have below code in angularjs part:
bolouk.js:
'use strict';
var app = angular.module('app');
app.controller('BoloukCtrl', ['$scope', 'Bolouks', function($scope, Bolouks){
$scope.save = function(){
Bolouks.create($scope.bolouk).then(function(data){
$scope.saveBolouk = data;
},function(err){
$scope.err = err;
}
);
};
}]);
boloukService.js:
'use strict';
var app = angular.module('boloukService', ['ngResource']);
app.factory('Bolouks', function($resource) {
return $resource('/api/bolouks.json', {}, {
create: { method: 'POST', isArray: false }
});
});
and I have below code in rails server:
bolouks_controller.rb:
def create
#bolouk = Bolouk.create(bolouk_params)
if #bolouk.valid?
##bolouk.save
respond_with #bolouk, :location => api_bolouks_path
else
respond_with #bolouk.errors, :location => api_bolouks_path
end
end
private
def bolouk_params
params.require(:bolouk).permit(:boloukcode, :north, :south, :east, :west)
end
Request send to rails server correctly and data is save to database right, but I cannot get response of request and when I run function`, I get below error in chrome console:
TypeError: undefined is not a function
at Scope.$scope.save (http://localhost:3000/assets/controllers/bolouk.js?body=1:19:39)
at http://localhost:3000/assets/angular.js?body=1:10973:21
at http://localhost:3000/assets/angular.js?body=1:20088:17
at Scope.$eval (http://localhost:3000/assets/angular.js?body=1:12752:28)
at Scope.$apply (http://localhost:3000/assets/angular.js?body=1:12850:23)
at HTMLFormElement.<anonymous> (http://localhost:3000/assets/angular.js?body=1:20087:21)
at HTMLFormElement.jQuery.event.dispatch (http://localhost:3000/assets/templates/jquery-1.10.2.js?body=1:4627:9)
at HTMLFormElement.elemData.handle (http://localhost:3000/assets/templates/jquery-1.10.2.js?body=1:4295:46)
I think I don't use .then correctly in angularjs controller, I check $q method too, but again get this error. Any one have idea to solve this problem?
you have assign both module in same variable. this may conflict your code. so use this code:
bolouk.js:
'use strict';
var app = angular.module('app',['ngResource']);
app.controller('BoloukCtrl', ['$scope', 'Bolouks', function($scope, Bolouks){
$scope.save = function(){
Bolouks.create($scope.bolouk).$promise.then(function(data){
$scope.saveBolouk = data;
})
.catch(function (err) {
console.log(err);
})
};
}]);
boloukService.js:
'use strict';
app.factory('Bolouks', function($resource) {
return $resource('/api/bolouks.json', {}, {
create: { method: 'POST', isArray: false }
});
});
var app = angular.module('app',['boloukService']);
app.controller('BoloukCtrl', ['$scope', 'Bolouks', function($scope, Bolouks){
$scope.save = function(){
var user = Bolouks.get();
user.get(function(resp) {
//request successful
}, function(err) {
//request error
});
};
}]);
angular.module('boloukService', ['ngResource']);
app.factory('Bolouks', function($resource) {
var savedData = {}
function get() {
return $resource('/api/bolouks.json', {}, {
create: { method: 'POST', isArray: false}
});
}
return {
get: get
}
});
try this one :)

Categories

Resources