ng-file-upload returns 401 - angularjs

I'm using ng-file-upload to upload PDF to a Spring MVC back server on a different port. I have another requests made with normal $http, but when I use the Upload object I always get error 401. I can see on the browser's network tab that Cookie header is not send, but in the other cases it does.
Here is my code:
Upload.upload({
url: $http.defaults.backUrl + '/oficio/upload',
data: {file: file, 'username': 'Alex'},
withCredentials: true
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
The request goes through my CORS filter, I'm sure because it sets the right headers, but the request doesn't send the Cookie header:
And this is the response:
When use $http, I don't get that error, this is a sample request with $http:
$http({
method: 'POST',
url: $http.defaults.backUrl + '/oficio/upload',
data: data,
headers: {
'Content-Type': undefined
}
});
When $http I can get the file, but canĀ“t track the progress.
Any help will be appreciated.

Related

Ng file upload with another data

I want to add my uploaded file by ng-file-upload to another data which i sending to my Java backend. I wondering how to do it, when I have to put url in my .upload. In this case that can't work cause sendMail sending firstly file, next the text data. How can I fix it?
$scope.sendMail = function(){
$scope.uploadFiles = function(file) {
$scope.attach = file;
file.upload = Upload.upload({
data: {file: file}
});
}
$scope.emailData = new EmailData();
$scope.emailData.to = "myMail#a.com";
$scope.emailData.from = "yourMail#a.com";
$scope.emailData.type = "TYPE";
$scope.emailData.title = $scope.data.title;
$scope.emailData.descr = $scope.data.description;
$scope.emailData.template = "template";
$scope.emailData.file = $scope.attach;
$http.post("sendemail", $scope.emailData, {headers: {'Content-Type': 'application/json'} })
.then(function (response) {
$scope.succes = true;
},
function(fail) {
$scope.error = true;
});
}
this is example from ng-file-upload Github
$scope.upload = function (file) {
Upload.upload({
url: 'upload/url',
data: {file: file, 'username': $scope.username}
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
};
as you see you can send what you want inside data
use content-type: multipart form/data & make use form-data; have a look at this link https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

How to show something on frontend (Angular) when node app crashed

I have developed an application in mean stack and there are some processes which took extra time to perform such as inserting thousands of data into mongodb.
It crashes sometime and the UI of the application left hanging in the middle.
Is there any way to overcome this and show some error message to user when app crashes.
Below is some code example :-
Upload.upload({
url: '/api/uploadarchive',
data: {file: file}
}).then(function (resp) {
$scope.progress = false;
console.log('Success ');
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
//console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
console.log('progress: ' + progressPercentage + '% ');
});
I'd recommend using $http interceptors. Interceptors will help you to handle errors in a generic way so you will not have to use error callback for each request separately. For example you can use responseError interceptor to check if response status of any request is 404 and in such case redirect to an error page:
define factory with your interceptors:
yourAppModule.factory('myHttpInterceptor', function($q, $state, dependency2) {
return {
'responseError': function(rejection) {
var status = rejection.status;
if (status === 404) {
$state.go('errorPage');
}
return $q.reject(rejection);
}
};
});
and then register it inside your application config:
$httpProvider.interceptors.push('myHttpInterceptor');

show success page if form is successfully submitted

How do i track if a upload is success and redirect to a certain page using angular and ng-file upload (https://github.com/danialfarid/ng-file-upload)
Currently it uploads the file but i need to show an error if the form is failed to insert to mysql or show the success page
Below is my angular function
Upload.upload({
url: 'api/upload-image.php',
method: 'POST',
file: file,
data: {
'awesomeThings': $scope.awesomeThings,
'targetPath' : '/media/'
}
})
in my php code
$status = $this->Upload_tools->add($data);
If an upload is access status will return true or else false
if success i want to show this page
$location.path('/show/'+qid);
See example code in ng-file-upload read.me:
$scope.upload = function (file) {
Upload.upload({
url: 'upload/url',
data: {file: file, 'username': $scope.username}
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
Now, your code will be something like this:
$scope.upload = function (file) {
Upload.upload({
url: 'api/upload-image.php',
method: 'POST',
file: file,
data: {
'awesomeThings': $scope.awesomeThings,
'targetPath' : '/media/'
}
}).then(function (resp) {
//Success case code
$location.path('/show/'+qid);
}, function (resp) {
//Error case code
}, function (evt) {
//progress calculation
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});

files are not storing in local using ngfileupload

I am trying to upload files using Node Api on server and i m using ngfileupload angular Module to handle image on front end.
below is my code:
app.controller('MyCtrl',['Upload','$window',function(Upload,$window){
var vm = this;
vm.submit = function(){
if (vm.upload_form.file.$valid && vm.file) {
vm.upload(vm.file);
}
}
vm.upload = function (file) {
Upload.upload({
url: '/api/upload',
data:{file:file} model
}).then(function (resp) {
if(resp.data.error_code === 0){ //validate success
$window.alert('Success ' + resp.config.data.file.name + 'uploaded. Response: ');
} else {
$window.alert('an error occured');
}
}, function (resp) {
console.log('Error status: ' + resp.status);
$window.alert('Error status: ' + resp.status);
}, function (evt) {
console.log(evt);
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
vm.progress = 'progress: ' + progressPercentage + '% ';
});
};
}]);
and my node api code is
apiRoutes.put('/upload', function(req, res){
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function(fieldname,file,filename){
var filePath=path.join(__dirname, './public/file', filename);
fstream=fs.createWriteStream(filePath);
file.pipe(fstream);
fstream.on('close', function(){
console.log("File Saved...........");
});
});
});
Now problem is that , when i hit upload button its showing an alert Error Status:404 and an error:
Not allowed to load local resource: file:///C:/fakepath/IMG-20160126-WA0013.jpg
I dont know how to fix it...
please help me
NgFileUpload send POST request by default. Your api router accepts PUT requests only.
Try to change apiRoutes.put... to apiRouter.post... or set
Upload.upload({
url: '/api/upload',
data: {file:file},
method: 'PUT'
})

Unexpected field ng-file-upload

I'm new on AngularJS and I'm trying to upload an image with ng-file-upload
My task was to translate an Ionic app to a web app so I've to reused same routes.
<button ngf-select="upload($file)" ng-model="file">Select</button>
$scope.upload = function (file) {
$scope.event.headerPictures.push(file);
console.log($scope.event);
console.log(file);
if (file && !file.$error) {
Upload.upload({
url: $config.baseUrl + '/api/event/upload-picture',
method: "POST",
headers: {"Authorization" : "token=" + userService.getToken()},
file: file,
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
};
};
I'm still getting the same error with many different syntaxe :
Error: Unexpected field
Can someone tell me what am I missing ?
Sorry to guess in an answer but with an unexpected field error I would think the line of your code with the extra comma delimiter is the issue.
file: file, should be file: file
Hope this helps. I would have commented this but my reputation is too low for comments still :)

Resources