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:
Related
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
});
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.
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);
});
Actually, I am uploading image using service, image uploaded successfully, but I want responded data to the function in controller.
Controller:
adminApp.controller('imageController', ['$scope', 'fileUpload', 'Images',function ($scope, fileUpload, Images) {
$scope.uploadFile = function (data) {
console.log(data);
var file = data.myFile;
console.log('file is ');
console.dir(file);
var uploadUrl = "/image";
fileUpload.uploadFileToUrl(file, data, uploadUrl);
// $scope.images.push();
};
}]);
Service:
adminApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, data, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
fd.append('owner_id', data.owner_id);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function (data) {
// return data;
})
.error(function () {
});
}
}]);
laravel (backhand):
public function store(Request $request)
{
$image = $request->file('file');
$image = $this->imageRepository->makeImage($image);
return $image;
}
I function in service return responded data from backhand to controller, so I can push the value to $scope.images in controllers function.
You can take advantage of angular $q here.
Updated Service Function
this.uploadFileToUrl = function (file, data, uploadUrl) {
var defer = $q.defer();
var fd = new FormData();
fd.append('file', file);
fd.append('owner_id', data.owner_id);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function (data) {
// return data;
defer.resolve(data);
})
.error(function (error) {
defer.reject(error);
});
}
return defer.promise;
}]);
In your controller, you can use the function as
fileUpload.uploadFileToUrl(file, data, uploadUrl).then(function(response){
//response contains your data form service
}).catch(function(error){
// error variable contains error data from service.
});
the code is not tested.. but it should work or very close.
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 :)