Erros Post Uploaded image with angularJS - 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 :)

Related

Redirecting after upload

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');
});

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);
});

Upload file using Angular $resource

I am trying to upload a file using angular $resource, i am able to hit the Api but the request doesn't have any file. I have tried the solution here as well: AngularJS: Upload files using $resource (solution)
My Controller:
var formData = new FormData();
formData.append('file', $scope.file);
appService.manualDataUpload(formData)
.then(function (response) {
//do something here
})
.catch(function (error) {
logger.error('An error occurred while uploading the file !', error);
});
My Factory service:
function manualDataUpload(formData) {
var /** #type {angular.Resource} */
manualDataUploadResource = $resource(serviceBase + '/ManualDataUpload', formData,
{
save: {
method: 'POST',
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}
});
return manualDataUploadResource
.save()
.$promise;
}
Removing the formData from $resource and adding in the body worked.
function manualDataUpload(formData) {
var /** #type {angular.Resource} */
manualDataUploadResource = $resource(serviceBase + '/ManualDataUpload', {},
{
save: {
method: 'POST',
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}
});
return manualDataUploadResource
.save(formData)
.$promise;
}

AngularJS Error while Uploading A File

This code:
App.service('fileUpload', ['$http', function($http) {
this.uploadFileToUrl = function(file, uploadUrl) {
console.log("inside upload file service js ");
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
})
.success(function(response) {
console.log("file uploaded sucessfully " + response);
})
.error(function(error) {
console.log("Error while uploading file " + JSON.stringify(error));
});
}
}]);
Produces this error: "container has no method handling POST"
{"error":{"name":"Error","status":404,"message":"Shared class \"container\" has no method handling POST /5555-1111","statusCode":404,"stack":"Error:

how to upload a file using $resource in angularjs

I want to post form data using $resource, before I was using $http as following :
upload : function(file){
let fd = new FormData();
fd.append('file', file);
$http.post('http://localhost:8080/fileUpload', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
and now I want to use $resource instead, and this is what I tried to do but it didn't work :
upload : function(file){
let fd = new FormData();
fd.append('file', file);
$resource('http://localhost:8080/fileUpload/:id',fd, {
create: {
method: "POST",
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}
});
}
Edit (Solution) :
From this post AngularJS: Upload files using $resource (solution) there was two solutions the first one which was pointed out by #juandemarco was to configure the $http service but this will transform each and every request made by AngularJS, so the second one which was pointed out by #timetowonder was a better solution since I need to define this behavior only for those $resources that actually need it, so I tried as following :
in my controller :
var fd = new FormData();
fd.append('identityDocUpload', $scope.identityDocUpload);
fileUploadService.create({}, fd).$promise.then(function (res) {
console.log('success');
}).catch(function (err) {
console.log('err');
});
my service :
app
.factory('fileUploadService', function ($resource) {
return $resource('http://localhost:8080/fileUpload/:id', { id: "#id" }, {
create: {
method: "POST",
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}
});
});
As pointed out here, you CAN do it the way explained, but you'll have some browser version limitation.
In the case below, he's uploading an image.
AngularJS: Upload files using $resource (solution)

Resources