Redirecting after upload - angularjs

I'm trying to redirect after a file upload but when I try to redirect on AngularJS side, it is not working.
Node.js :
app.post('/upload', upload.single('propt'), function (req, res) {
res.writeHead(200, {"Content-Type": "text/html; charset=utf-8"});
res.send();
});
AngularJS :
$scope.uploadFile = function () {
var fichier = $scope.monFichier;
var uploadUrl = "/upload";
console.dir(fichier);
var fd = new FormData();
fd.append('file', fichier);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }
})
.then(function () {
$window.location.href = '/users.html';
});
}
UPDATE : The "then" part is not executed (I tried with a simple console.log() to test it)

you redirect the page by using this code
$window.location.href = '/users.html';
window.location.href = '/users.html';

Try $location
You would need to inject $location in the controller and $location.path('/user') would redirect to http://example.com/#/user
.then(function () {
$location.path('/user');
});

Related

AngularJS: angular.js:13920 TypeError: Cannot read property 'then' of undefined

I am calling a back-end service using angularJS to upload multipart file I am encountering an error. the response comes to my service but from there I cannot get the response to my angular controller due to the above promise error.
fileUploadService:
(function() {
'use strict';
angular
.module('module')
.factory('FileUpload', FileUpload);
FileUpload.$inject = ['$http'];
function FileUpload($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(response){
})
.error(function(error){
});
}
return this;
}
})();
controller.js:
$scope.onFilesSelected = function(files) {
var uploadUrl = "/api//customer/logo";
FileUpload.uploadFileToUrl(files[0], uploadUrl).then(
function(result){
var logo = FileUpload.getResponse();
vm.setLogo(logo);
// $scope.errors = FileUpload.getResponse();
}, function(error) {
alert('error');
});
};
Your uploadFileToUrl() function has no return statement so it returns undefined. I guess you meant to return the promise returned by $http:
this.uploadFileToUrl = function(file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
// Notice the return statement below
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(response){
})
.error(function(error){
});
}
You didn't return any values. So do return response inside the success and error callback as below
.success(function(response){
return response;
})
.error(function(error){
return error
});

How to pass $scope variable data into node.js backend server file?

I have json data in $scope variable and i want to use that $scope variable inside my backend app.js node file.
This is my backend file app.js:
app.post('/upload', upload.single('file'), function(req, res) {
var XLSX = require('xlsx');
var workbook = XLSX.readFile('./uploads/' + req.file.filename);
var sheet_name_list = workbook.SheetNames;
var data = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
//var values = [];
console.log(data);
return res.status(200).send(data);
});
app.post('/api/uploadlast',api.addNewContact, function(req,res){
Contact.bulkCreate(excels).then(function(users) {
return res.status(200).send(users);
}).catch(Sequelize.ValidationError, function(err) {
return res.status(422).send(err.errors[0].message);
}).catch(function(err) {
return res.status(400).send(err.message);
});
})
This is my controller file:
$scope.uploadFile = function() {
var file = $scope.myFile;
var uploadUrl = "/upload";
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
})
.then(function(response) {
//$state.reload();
$scope.excels = response.data;
console.log("success!!");
})
.catch(function() {
console.log("error!!");
});
}
$scope.uploadLast = function() {
$http.post('/api/uploadlast').then(function(response) {
$state.reload();
});
}
})
I want to get $scope.excels data into my backend to bulkcreate into databases.
You can pass any data with a post request as the second parameter of $http.post(). So you can do something like:
$scope.uploadLast = function() {
var data = {
excels: $scope.excels
};
$http.post('/api/uploadlast', data).then(function(response) {
$state.reload();
});
}
And in your backend, you can access it like:
app.post('/api/uploadlast',api.addNewContact, function(req, res){
var data = req.body.excels;
Contact.bulkCreate(data).then(function(users) {
return res.status(200).send(users);
}).catch(Sequelize.ValidationError, function(err) {
return res.status(422).send(err.errors[0].message);
}).catch(function(err) {
return res.status(400).send(err.message);
});
});

How to set token value in headers when uploading a file angular

I am uploading a file using angular and node.js API.
I am following this link to upload a file.
In this tutorial we need to set header headers: {'Content-Type': undefined}
On other hand I need to set headers value for authentication token . For that I am setting default headers value like as $http.defaults.headers.common.Authorization = $cookieStore.get('token');
Now when I uploading a file then a error is shwoing i.e
Error: Can't set headers after they are sent.
Now please let me know how can I resolve this..
Or any solution to achieve this.
Thanks
Below is the Service and Controller for file upload
app.service('fileUpload', ['$http','$cookieStore', function ($http, $cookieStore) {
this.uploadFileToUrl = function(file, uploadUrl){
var token = $cookieStore.get('token') ;
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {transformRequest: angular.identity,headers: {'Content-Type': undefined} })
.success(function(res){
})
.error(function(){
});
}
}]);
app.controller('csvCtrl', function($scope, fileUpload){
$scope.importcsv=function(){
var file=$scope.myFile;
var uploadUrl="/api/parsecsv";
fileUpload.uploadFileToUrl(file, uploadUrl);
}
});
This should get you to the point of being able to apply the header:
app.service('fileUpload', ['$http', '$cookieStore', function ($http, $cookieStore) {
this.uploadFileToUrl = function (file, uploadUrl) {
var token = $cookieStore.get('token');
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd,
{
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
'Authorization': token
}
})
.success(function (res) {
})
.error(function () {
});
}
}]);
Once you get that working, you can set the default headers with an interceptor.

How to send data along with file in http POST (angularjs + expressjs)?

Situation
I implemented file uploading. Front-end code is taken from popular tutorial. I send POST in service:
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(){
});
}
}]);
Typical multer usage in back-end:
exports.postFile = function (req, res) {
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, '../documents/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
upload(req, res, function (err) {
if (err) {
res.json({error_code: 1, err_desc: err});
return;
}
res.json({error_code: 0, err_desc: null});
})
};
That works.
Question
How to send some data in the same POST, let say string "additional info"?
What I tried
I tried to add data in service, i.e.:
...
var fd = new FormData();
fd.append('file', file);
fd.append('model', 'additional info');
$http.post(uploadUrl, fd, {...})
It seems to be sent, but I don't know how to receive it in back-end. Tried to find it in req (without success).
To send data (i.e. json) and file in one POST request add both to form data:
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
var info = {
"text":"additional info"
};
fd.append('data', angular.toJson(info));
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
On server side it's in req.body.data, so it can be received i.e. like this:
upload(req, res, function (err) {
if (err) {
res.json({error_code: 1, err_desc: err});
return;
}
console.log(req.body.data);
res.json({error_code: 0, err_desc: null});
})
You can get the file from req.files and save it with fs.writeFile.
fs.readFile(req.files.formInput.path, function (err, data) {
fs.writeFile(newPath, data, function (err) {
if (err) {
throw err;
}
console.log("File Uploaded");
});
});
You can do something like this:
$http({
url: url,
method: 'POST',
data: json_data,
headers: {'Content-Type': 'application/json'}
}).then(function(response) {
var res = response.data;
console.log(res);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Or just add the data property to your function.
var userObject = {
email: $scope.user.email,
password: $scope.user.password,
fullName: $scope.user.fullName
};
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
data: userObject,
headers: {'Content-Type': 'application/json'}
})
You can try something like this on the backend.
req.on('data', function (chunk) {
console.log(chunk);
});

Erros Post Uploaded image with angularJS

I have question about upload-ing images with angularJS.
I'm using this code for upload image http://jsfiddle.net/sc1qnw4n/, that's code already made by someone.
$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);
});
}
But when I press upload image i got this:
error Cannot POST /imageURL
Has anyone had the same problem? Thank you :)

Resources