400 Bad request while sending restful request using angularJS - angularjs

I am using angularJs and rest controllers for making web service call. I am getting 400 bad request. When I was making a request to change the status of the user then I am getting the error. Please find the below code for js file, controller and UI.
Js Controller-
var user=angular.module('userApp', ['ngAnimate']);
user.controller('userController',function($scope,$http){
var urlBase=window.location.pathname;
$scope.selection = [];
$scope.toggle=true;
$scope.statuses=['YES','NO'];
$scope.sortType= 'name'; // set the default sort type
$scope.sortReverse= false; // set the default sort order
$scope.searchUser= ''; // set the default search/filter term
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
//get all users and display initially
$http.get(urlBase+"/users")
.success(function(data){
$scope.users = data;
});
$scope.addUser = function addUser() {
if($scope.firstName=="" || $scope.lastName=="" || $scope.email == "" || $scope.mobile == ""|| $scope.status == ""){
alert("Insufficient Data! Please provide values for task name, description, priortiy and status");
}
else{
$http.post(urlBase + '/users/insert/' +$scope.firstName+'/'+$scope.lastName+'/'+$scope.email+'/'+$scope.mobile+'/'+$scope.status)
.success(function(data) {
$scope.users = data;
$scope.firstName="";
$scope.lastName="";
$scope.email="";
$scope.mobile="";
$scope.status="";
$scope.toggle='!toggle';
});
}
};
$scope.archiveUser = function archiveUser(id){
console.log(":: Value of id :"+id);
$http.post(urlBase+'users/archive/'+id)
.success(function(data) {
$scope.users = data;
console.log(":: Data updated and displayed.")
})
.failure(function(data){
alert("Failed to archieve task ::"+data);
});
};
});
A part in User interface where the code is being called , i am using ng-repeat for displaying values and then on click of button calling archiveUser(). Id value is coming fine.
<button class="btn" ng-Click='archiveUser(x.id)'><i class="fa fa-archive"></i></button>
Spring Controller for handling request-
#RequestMapping(value="users/archive/{userIds}",method = RequestMethod.POST,headers="Accept=application/json")
public List<User> archiveUser(#PathVariable int userId) {
User user = new User();
user=userService.getUserService(userId);
List<User> users=userService.getAllUserService();
return users;
}

The problem was with 's' as Paqman commented. I removed 's' and then save & tried, got the correct result that was expecting. Thanks Paqman.

Related

How to use cookies outside controller?

I've setup cookies inside a Login Controller. Whenever I'm trying to get the values of cookies outside of controller it's throwing an error. please check this out what I'm missing.
Controller After i get success response I'm setting cookies
app.controller('AngularLoginController', ['$scope','$http','$cookies','$rootScope', function($scope, $http,
$cookies,$rootScope) {
$scope.loginForm = function() {
$http.post("login.php", {
'email' :$scope.inputData.email,
'password':$scope.inputData.password
}).success(function(data) {
console.log(data);
if ( data != 'wrong') {
var loggedIn = $cookies.get('loggedIn');
// Putting cookies
$cookies['myCookieArray']= {'loggedIn':true,'username':data};
getmycookiesback = $cookies['myCookieArray'];
window.location.href = '#/userlist';
$rootScope.display = true;
$rootScope.username = getmycookiesback.username;
}
else {
$scope.errorMsg = "Invalid Email and Password";
}
})
}
}]);
After I login it calls AngularLoginController and set Cookies values after success Response.
Outside Controller if I'm comparing value of cookies it's throwing error getmycookiesback is not defined
var onlyLoggedIn = function ($location,$q,$cookies,$rootScope) {
var deferred = $q.defer();
var url = $location.absUrl();
if (getmycookiesback.loggedIn === "undefined") { // Error on This line
deferred.reject();
window.location.href = '#/login';
}
else{
deferred.resolve();
$rootScope.display = true;
$rootScope.username = getmycookiesback.username;
window.location.href = url;
alert(getmycookiesback.username);
//$cookies.remove('loggedIn');
return true;
}
return deferred.promise;
};
Why it's undefined if i have defined it in Controller.
Is there another way i can get value of cookies outside controller ?
Of course it is undefined; it appears to be a local variable in that function scope.
You may want to take a look at Angular Services for things you want to access globally - you may want to implement a function on a service to do this, or store that information locally within the service and provide a function to access it - take a look here.

I send http post request with angular but it does not go to the asp.net mvc action and returns html layout tags

I am doing an angular application with asp.net mvc and i made a registration form with identity, I have layout and index mvc view which i just write in it ng-view tag and i inject html pages in it, I am doing a http post request from angular controller to mvc action method but the request does not go to the mvc action, whereas when i change th views to mvc views and make a templateUrl in angular map to mvc method it works well.
Can any one help me in this problem.
[HttpPost]
[AllowAnonymous]
public async Task<JsonResult> Register(RegisterViewModel model)
{
string message = "";
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
FirstName = model.FirstName,
MiddleName = model.MiddleName,
LastName = model.LastName,
UserName = model.Email,
Email = model.Email,
UserStatus = UserStatus.Waiting
};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
message = "Success";
}
else
{
AddErrors(result);
message = "InvalidEmail";
}
}
else
{
message = "Failed!";
}
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
and this is my angular controller
MyApp.controller('RegisterController', ['$scope','$http',function ($scope, $http) {
$scope.message = '';
$scope.isFormValid = false;
//Check Form Validation
$scope.$watch('f1.$valid', function (newValue) {
$scope.isFormValid = newValue;
});
//Save Data
$scope.SaveData = function (data) {
$scope.submitted = true;
$scope.message = '';
if ($scope.isFormValid) {
$http({
method: 'POST',
url: '/Account/Register',
data: data
}).then(function (response) {
// check your response (if a success status code was resolved)
console.log(response.data);
}, function (error) {
// check your error response
console.log(error);
});
} else {
$scope.message = "Please Fill the blanks";
}
}
}]);
and this is my html page:
<div ng-controller="RegisterController">
<form name="f1" ng-submit="SaveData(user)" novalidate>
controls here
</form
1) Check your browser console for any javascript errors, if you have any, resolve them and try again!
2) Check you have the correct ActionMethodSelectorAttribute attribute ([HttpPost]) over your controller method and that your method name is spelt correctly.
3) Check that you have the correct path in your request.
4) Check you are sending the correct data to the controller!!!
5) Check that the method is public.
6) Check that you are authorised to access that controller/method.
7) Check that you don't have any duplicate method names with either, a) the same parameters and name (if your not using an ActionMethodSelectorAttribute, or b) the same names and method select attributes.
8) Remove all parameters from your method, put a breakpoint at the start of the method, and try making the request and see if it hits the breakpoint. If it works without parameters and not with, then you are not passing the correct required data into the method.
9) Make your request and check the response!! (example below):
// make your request
$http({
method: 'POST',
url: '/Controller/Method',
data: {
foo: bar
}
}).then(function(response) {
// check your response (if a success status code was resolved)
console.log(response);
}, function(error) {
// check your error response
console.log(error);
});
If you have a 404 then your method was not found, if you have a 500 then something blew up in your code, if you have a 401 then you are unauthorised etc... This is really useful to actually know what is going on with your request...
10) Check your application is running!

private chat using socket.id on socket.io

i am fresher at nodejs and socket.io. i am trying to made a chat application using nodejs, socket.io and angularjs in express framework. i am lacking basic idea how chat is performed privately.up to this stage my code works chatting in a group of connected users. here is my server code
var server = require('http').Server(app);
var io = require('socket.io')(server);
var socket = require('./routes/socket.js');
server.listen(8000);
console.log('server listening on port:8000');
io.on('connection',socket);
and my main socket file consit code like:
module.exports = function(socket){
console.log('connected'+' '+'socketId :'+socket.id);
//console.log(req.session.id);
var users =[];
socket.emit(socket.id);
socket.on('username',function(data){
users.push({id:socket.id,message:data.username});
socket.emit('username', users)
})
socket.on('typing',function(data){
//socket.emit('typing',{message:"helo angular"});
socket.broadcast.emit('typing',{message:data.message});
});
socket.on('typing-stop',function(data){
//socket.emit('typing',{message:"helo angular"});
debugger;
socket.broadcast.emit('typing-stop',{message:data.message});
});
socket.on('new-user',function(data){
socket.emit('new-user',data);
socket.broadcast.emit('new-user',data);
})
socket.on('message',function(data){
users.push({message:data.message});
socket.emit('message',{id:socket.id,message:data.message});
socket.broadcast.emit('message',{id:socket.id,message:data.message});// emit the message to every one connected in server
})
socket.on('disconnect',function(){
console.log('user disconnected');
socket.broadcast.emit('disconnected',{'message':'user left the chat room'});
});
}
i am abe to load all the users who get logged in my app.
all i want is to click to the available and start private messaging, till now chat is public everyone connected in server can see message.
my angularjs controller code goes like:
function orgController(notifyService, chatSocket, $state,$http) {
chatSocket.connect();
var vm = this;
vm.sendMessage = sendMessage;
vm.messages = [];
vm.users = [];
var id = $state.params.id;
$http.get('/users/' + id).then(function(result) {
console.log(result.data);
vm.userData = result.data;
chatSocket.emit('new-user', { 'username': result.data.details.firstName + ' ' + result.data.details.lastName });
});
chatSocket.on('new-user',function(data){
vm.users.push(data);
})
function sendMessage(msg) {
//console.log(msg);
if (msg != null && msg != '') {
chatSocket.emit('message', { message: msg });
vm.msg = '';
} else {
vm.msg = '';
}
}
chatSocket.on('message', function(data) {
//debugger;
console.log(data);
vm.messages.push(data);
});
}
NOTE: i have included angular-socket.io modules and inject its dependency in a service called chatSocket which only return socketFactory.
now i want to click in a user from logged in userlist and start communication. how can i do it from (socket.id). which socket generates or from session id? anyone has better way of doing such. any suggestion and response are highly appreciated.
Basically what you need to do is emit an event to a specific socket like this.
io.to(socket.id).emit('privateMessage', {message: <message goes here>});
then on the client side
socket.on('privateMessage', function(data){
var message = data.message;
//do stuff, display message etc...
});

Uploading images with Mongoose, Express and AngularJS

I know this has been asked many times before, and I have read almost all I could find about the subject, namely:
https://stackoverflow.com/a/25022437/1031184
Uploading images using Node.js, Express, and Mongoose
Those are the best I have found so far. My problem is tho that they still aren't very clear, there is very little documentation online at all about this and the discussion seems aimed at people who are much more advanced than I am.
So with that I would really love it if someone could please walk me though how to upload images using Mongoose, Express & AngularJS. I am actually using the MEAN fullstack. (this generator to be precise – https://github.com/DaftMonk/generator-angular-fullstack)
AddController:
'use strict';
angular.module('lumicaApp')
.controller('ProjectAddCtrl', ['$scope', '$location', '$log', 'projectsModel', 'users', 'types', function ($scope, $location, $log, projectsModel, users, types) {
$scope.dismiss = function () {
$scope.$dismiss();
};
$scope.users = users;
$scope.types = types;
$scope.project = {
name: null,
type: null,
images: {
thumbnail: null // I want to add the uploaded images _id here to reference with mongoose populate.
},
users: null
};
$scope.save = function () {
$log.info($scope.project);
projectsModel.post($scope.project).then(function (project) {
$scope.$dismiss();
});
}
}]);
I want to add the Images ID reference to project.images.thumbnail but I want to store all the information inside an Image Object using the following Schema:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ImageSchema = new Schema({
fileName: String,
url: String,
contentType: String,
size: String,
dimensions: String
});
module.exports = mongoose.model('Image', ImageSchema);
I have also added the following https://github.com/nervgh/angular-file-upload to my bower packages.
As I say I just can't figure out how to tie it all together. And I'm not even sure if what I am trying to do is the correct way either.
--------------------------------------------------------------------------\
UPDATE:
Here is what I now have, I have added some comments detailing how I would like it to work, unfortunately I still haven't managed to get this working, I can't even get the image to start uploading, never mind uploading to S3. Sorry to be a pain but I am just finding this particularly confusing, which surprises me.
client/app/people/add/add.controller.js
'use strict';
angular.module('lumicaApp')
.controller('AddPersonCtrl', ['$scope', '$http', '$location', '$window', '$log', 'Auth', 'FileUploader', 'projects', 'usersModel', function ($scope, $http, $location, $window, $log, Auth, FileUploader, projects, usersModel) {
$scope.dismiss = function () {
$scope.$dismiss();
};
$scope.newResource = {};
// Upload Profile Image
$scope.onUploadSelect = function($files) {
$scope.newResource.newUploadName = $files[0].name;
$http
.post('/api/uploads', {
uploadName: newResource.newUploadName,
upload: newResource.newUpload
})
.success(function(data) {
newResource.upload = data; // To be saved later
});
};
$log.info($scope.newResource);
//Get Projects List
$scope.projects = projects;
//Register New User
$scope.user = {};
$scope.errors = {};
$scope.register = function(form) {
$scope.submitted = true;
if(form.$valid) {
Auth.createUser({
firstName: $scope.user.firstName,
lastName: $scope.user.lastName,
username: $scope.user.username,
profileImage: $scope.user.profileImage, // I want to add the _id reference for the image here to I can populate it with 'ImageSchema' using mongoose to get the image details(Name, URL, FileSize, ContentType, ETC)
assigned: {
teams: null,
projects: $scope.user.assigned.projects
},
email: $scope.user.email,
password: $scope.user.password
})
.then( function() {
// Account created, redirect to home
//$location.path('/');
$scope.$dismiss();
})
.catch( function(err) {
err = err.data;
$scope.errors = {};
// Update validity of form fields that match the mongoose errors
angular.forEach(err.errors, function(error, field) {
form[field].$setValidity('mongoose', false);
$scope.errors[field] = error.message;
});
});
}
};
$scope.loginOauth = function(provider) {
$window.location.href = '/auth/' + provider;
};
}]);
server/api/image/image.model.js I would like to store all image information here and use this to populate profileImage in people controller.
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ImageSchema = new Schema({
fileName: String,
url: String, // Should store the URL of image on S3.
contentType: String,
size: String,
dimensions: String
});
module.exports = mongoose.model('Image', ImageSchema);
client/app/people/add/add.jade
.modal-header
h3.modal-title Add {{ title }}
.modal-body
form(id="add-user" name='form', ng-submit='register(form)', novalidate='')
.form-group(ng-class='{ "has-success": form.firstName.$valid && submitted,\
"has-error": form.firstName.$invalid && submitted }')
label First Name
input.form-control(type='text', name='firstName', ng-model='user.firstName', required='')
p.help-block(ng-show='form.firstName.$error.required && submitted')
| First name is required
.form-group(ng-class='{ "has-success": form.lastName.$valid && submitted,\
"has-error": form.lastName.$invalid && submitted }')
label Last Name
input.form-control(type='text', name='lastName', ng-model='user.lastName', required='')
p.help-block(ng-show='form.lastName.$error.required && submitted')
| Last name is required
.form-group(ng-class='{ "has-success": form.username.$valid && submitted,\
"has-error": form.username.$invalid && submitted }')
label Username
input.form-control(type='text', name='username', ng-model='user.username', required='')
p.help-block(ng-show='form.username.$error.required && submitted')
| Last name is required
// Upload Profile Picture Here
.form-group
label Profile Image
input(type="file" ng-file-select="onUploadSelect($files)" ng-model="newResource.newUpload")
.form-group(ng-class='{ "has-success": form.email.$valid && submitted,\
"has-error": form.email.$invalid && submitted }')
label Email
input.form-control(type='email', name='email', ng-model='user.email', required='', mongoose-error='')
p.help-block(ng-show='form.email.$error.email && submitted')
| Doesn't look like a valid email.
p.help-block(ng-show='form.email.$error.required && submitted')
| What's your email address?
p.help-block(ng-show='form.email.$error.mongoose')
| {{ errors.email }}
.form-group(ng-class='{ "has-success": form.password.$valid && submitted,\
"has-error": form.password.$invalid && submitted }')
label Password
input.form-control(type='password', name='password', ng-model='user.password', ng-minlength='3', required='', mongoose-error='')
p.help-block(ng-show='(form.password.$error.minlength || form.password.$error.required) && submitted')
| Password must be at least 3 characters.
p.help-block(ng-show='form.password.$error.mongoose')
| {{ errors.password }}
.form-group
label Assign Project(s)
br
select(multiple ng-options="project._id as project.name for project in projects" ng-model="user.assigned.projects")
button.btn.btn-primary(ng-submit='register(form)') Save
pre(ng-bind="user | json")
.modal-footer
button.btn.btn-primary(type="submit" form="add-user") Save
button.btn.btn-warning(ng-click='dismiss()') Cancel
server/api/upload/index.js
'use strict';
var express = require('express');
var controller = require('./upload.controller');
var router = express.Router();
//router.get('/', controller.index);
//router.get('/:id', controller.show);
router.post('/', controller.create);
//router.put('/:id', controller.update);
//router.patch('/:id', controller.update);
//router.delete('/:id', controller.destroy);
module.exports = router;
server/api/upload/upload.controller.js
'use strict';
var _ = require('lodash');
//var Upload = require('./upload.model');
var aws = require('aws-sdk');
var config = require('../../config/environment');
var randomString = require('../../components/randomString');
// Creates a new upload in the DB.
exports.create = function(req, res) {
var s3 = new aws.S3();
var folder = randomString.generate(20); // I guess I do this because when the user downloads the file it will have the original file name.
var matches = req.body.upload.match(/data:([A-Za-z-+\/].+);base64,(.+)/);
if (matches === null || matches.length !== 3) {
return handleError(res, 'Invalid input string');
}
var uploadBody = new Buffer(matches[2], 'base64');
var params = {
Bucket: config.aws.bucketName,
Key: folder + '/' + req.body.uploadName,
Body: uploadBody,
ACL:'public-read'
};
s3.putObject(params, function(err, data) {
if (err)
console.log(err)
else {
console.log("Successfully uploaded data to my-uploads/" + folder + '/' + req.body.uploadName);
return res.json({
name: req.body.uploadName,
bucket: config.aws.bucketName,
key: folder
});
}
});
};
function handleError(res, err) {
return res.send(500, err);
}
server/config/environment/development.js
aws: {
key: 'XXXXXXXXXXXX',
secret: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
region: 'sydney',
bucketName: 'my-uploads'
}
All of this code is straight out of a project that depends heavily on this for large file uploads and images. Definitely checkout https://github.com/nervgh/angular-file-upload
In my view somewhere:
<div class="form-group">
<label>File Upload</label>
<input type="file" ng-file-select="onUploadSelect($files)" ng-model="newResource.newUpload">
</div>
Using the module angularFileUpload I then have in my controller:
$scope.onUploadSelect = function($files) {
$scope.newResource.newUploadName = $files[0].name;
};
https://github.com/nervgh/angular-file-upload
When the user clicks upload this gets executed where I send the file to be uploaded:
$http
.post('/api/uploads', {
uploadName: newResource.newUploadName,
upload: newResource.newUpload
})
.success(function(data) {
newResource.upload = data; // To be saved later
});
This request is sent to a controller that looks something like this:
'use strict';
var _ = require('lodash');
var aws = require('aws-sdk');
var config = require('../../config/environment');
var randomString = require('../../components/randomString');
// Creates a new upload in the DB.
exports.create = function(req, res) {
var s3 = new aws.S3();
var folder = randomString.generate(20); // I guess I do this because when the user downloads the file it will have the original file name.
var matches = req.body.upload.match(/data:([A-Za-z-+\/].+);base64,(.+)/);
if (matches === null || matches.length !== 3) {
return handleError(res, 'Invalid input string');
}
var uploadBody = new Buffer(matches[2], 'base64');
var params = {
Bucket: config.aws.bucketName,
Key: folder + '/' + req.body.uploadName,
Body: uploadBody,
ACL:'public-read'
};
s3.putObject(params, function(err, data) {
if (err)
console.log(err)
else {
console.log("Successfully uploaded data to csk3-uploads/" + folder + '/' + req.body.uploadName);
return res.json({
name: req.body.uploadName,
bucket: config.aws.bucketName,
key: folder
});
}
});
};
function handleError(res, err) {
return res.send(500, err);
}
server/components/randomString/index.js
'use strict';
module.exports.generate = function(textLength) {
textLength = textLength || 10;
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for(var i = 0; i < textLength; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
server/config/environment/development.js
server/api/upload/upload.controller.js
This is the way i used MEAN.JS for file upload.
Model
var UserSchema = new mongoose.Schema({
name:{type:String,required:true},
photo:Buffer // Image
});
Server Controller
var userPicture = function(req,res){ // Stores Picture for a user matching the ID.
user.findById(req.param('id'), function (err, user) {
console.log(req.files) // File from Client
if(req.files.file){ // If the Image exists
var fs = require('node-fs');
fs.readFile(req.files.file.path, function (dataErr, data) {
if(data) {
user.photo ='';
user.photo = data; // Assigns the image to the path.
user.save(function (saveerr, saveuser) {
if (saveerr) {
throw saveerr;
}
res.json(HttpStatus.OK, saveuser);
});
}
});
return
}
res.json(HttpStatus.BAD_REQUEST,{error:"Error in file upload"});
});
};
Client Controller
$scope.saveuserImage = function(){
$scope.upload = $upload.upload({ // Using $upload
url: '/user/'+$stateParams.id+'/userImage', // Direct Server Call.
method:'put',
data:'', // Where the image is going to be set.
file: $scope.file
}).progress(function (evt) {})
.success(function () {
var logo = new FileReader(); // FileReader.
$scope.onAttachmentSelect = function(file){
logo.onload = function (e) {
$scope.image = e.target.result; // Assigns the image on the $scope variable.
$scope.logoName = file[0].name; // Assigns the file name.
$scope.$apply();
};
logo.readAsDataURL(file[0]);
$scope.file = file[0];
$scope.getFileData = file[0].name
};
location.reload();
$scope.file = "";
$scope.hideUpload = 'true'
});
$scope.getFileData = '';
// location.reload()
};
Html
The ng-file-select is used to get the file from the client.
This works fine for me. Hope this helps.
Note: I have used HTML tag instead of jade. Suitable changes applicable while using jade.
As far as I can guess, you are binding the FileReader.onload() method inside the saveUserImage function, then the onload method will be never called as the function is never binded instead a user calls saveUserImage method before editing the image. After that, no image will be selected as the onload() method will not execute.
Try coding Client Controller it this way
//This goes outside your method and will handle the file selection.This must be executed when your `input(type=file)` is created. Then we will use ng-init to bind it.
$scope.onAttachmentSelect = function(){
var logo = new FileReader(); // FileReader.
logo.onload = function (event) {
console.log("THE IMAGE HAS LOADED");
var file = event.currentTarget.files[0]
console.log("FILENAME:"+file.name);
$scope.image = file;
$scope.logoName = file.name; // Assigns the file name.
$scope.$apply();
//Call save from here
$scope.saveuserImage();
};
logo.readAsDataURL(file[0]);
$scope.file = file[0];
$scope.getFileData = file[0].name
reader.readAsDataURL(file);
};
//The save method is called from the onload function (when you add a new file)
$scope.saveuserImage = function(){
console.log("STARGING UPLOAD");
$scope.upload = $upload.upload({ // Using $upload
url: '/user/'+$stateParams.id+'/userImage',
method:'put'
data:, $scope.image
file: $scope.file
}).progress(function (evt) {})
.success(function () {
location.reload();
$scope.file = "";
$scope.hideUpload = 'true'
});
$scope.getFileData = '';
// location.reload()
};
The HTML.
//There is the ng-init call to binding function onAttachmentSelect
<div class="form-group">
<label>File Upload</label>
<input type="file" ng-init="onAttachmentSelect" ng-model="newResource.newUpload">
</div>
Hope this clue may help you
EDIT*
Will try to explain you the different Steps you must follow to check your code:
1.- Is your input[type=file] showing? If showing, please select an image
2.- Is your input calling the onload when the image selected has changed? (a console.log should be printed with my code version)
3.- If it has been called. Make the operations you need before sending, inside the onload method (if possible)
4.- When this method has finished doing desired changes. Inform with ng-model or however you want, a variable in the object you prepared to upload, with the base64 string generated in the onload method.
When arriving this point, remember checking that:
As very big images could be sent over json with base64, it´s very important to remember changing the minimum json size in Express.js for your app to prevent rejects. This is done, for example in your server/app.js as this:
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb'}));
Remember also that the method reader.readAsDataURL(file) will give you a base64 string that could act as src of the image. You don´t need more than this. This base64 is what you can save in mongoose. Then, you can use ng-model to send a variable containing the base64 in the form with the "submit" button.
Then, in the Express.js endpoint that will handle your form, you will be able to decode the base64 string to a file, or to save the base64 directly on mongoose (storing images in the db is not much recommended if a lot of images is being to be loaded, or big ones desired, as the mongoDB query will be very slow).
Hope you can solve with those indications. If you still have some doubts, please comment and I´ll try to help
I'm also a noob using MEANJS, and this is how I made it work using ng-flow + FileReader:
HTML input:
<div flow-init
flow-files-added="processFiles($files)"
flow-files-submitted="$flow.upload()"
test-chunks="false">
<!-- flow-file-error="someHandlerMethod( $file, $message, $flow )" ! need to implement-->
<div class="drop" flow-drop ng-class="dropClass">
<span class="btn btn-default" flow-btn>Upload File</span>
<span class="btn btn-default" flow-btn flow-directory ng-show="$flow.supportDirectory">Upload Folder</span>
<b>OR</b>
Drag And Drop your file here
</div>
controller:
$scope.uploadedImage = 0;
// PREPARE FILE FOR UPLOAD
$scope.processFiles = function(flow){
var reader = new FileReader();
reader.onload = function(event) {
$scope.uploadedImage = event.target.result;
};
reader.onerror = function(event) {
console.error('File could not be read! Code ' + event.target.error.code);
};
reader.readAsDataURL(flow[0].file);
};
And on the server side the variable on the model receiving the value of uploadedImage is just of type string.
Fetching it back from the server didn't require any conversion:
<img src={{result.picture}} class="pic-image" alt="Pic"/>
Now just need to find out what to do with big files...

How to send post request through Angular to ASP.net web API

I am new to both angular and ASP.NET web API. in angular i get values from a form and try to pass it to the server through post request her is the code for angular.
app.controller('AddTrnController',['$scope', 'CategoriesService','$http', function($scope, CategoriesService, $http){
$scope.categories =[{}];
$scope.AddTrn = {};
function init(){
CategoriesService.getCategories("1")
.success(function(data){
$scope.categories = data;
})
.error(function(data, status, headers){alert(status);});
}
init();
$scope.change= function(option){
$scope.AddTrn.TrnID = option.CatID;
$scope.AddTrn.TrnAccount = 1;
};
$scope.UpdateTrans=function(){
alert("21312");
$http({method:"post",
url:'http://localhost:18678/api/Transaction',
params:"data:$scope.AddTrn"}
).success(function(){alert("succeeded");
}).error(function(){alert("faild");});
};
}]);
And her the the code for web API.
public HttpResponseMessage PostTransaction(String transaction)
{
if (ModelState.IsValid)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, transaction);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = transaction}));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
I always get failed response from angler and when i make breakpoint in API it dose not trigger.
The params option that you are using adds items to the query string, for a post you will probably want to use the data option instead, try changing the code to this:
$scope.UpdateTrans=function(){
alert("21312");
$http({method:"post",
url:'http://localhost:18678/api/Transaction',
data:$scope.AddTrn
}
).success(function(){alert("succeeded");
}).error(function(){alert("faild");});
};

Resources