How to upload a file with AngularJS? - javascript

I am trying to upload a file with AngularJS. This is my code:
HTML
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
JavaScript
$scope.uploadFile = function(){
var file = $scope.myFile;
var uploadUrl = "http://admin.localhost/images/patanjali/";
VariantService.uploadFileToUrl(file, uploadUrl);
};
VariantService.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(){
alert ('success');
})
.error(function(){
});
}
Although I can see the ('success') alert in my service, the file is not saving in the location provided in controller.
Can someone help me? What is missing?

It looks like you're using code from this jfiddle for your app:
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(){
});
}
}]);
While properly configured, this is only for posting data from the client side; the server also needs to be configured to accept/save the data. How you do this depends on your back-end tech stack.

I had same issue. I tried following code and my problem was solved.
var req = {
method: 'POST',
url: url,
headers: {
'Content-Type': "application/json",
},
data: data,
transformRequest: function(data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function(value, key) {
formData.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return formData;
}
}
$http(req)
.success(function(response) {
$scope.Models = response;
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert(data);
});

$scope.setFiles = function (element) {
$scope.$apply(function (scope) {
$scope.files = [];
for (var i = 0; i < element.files.length; i++) {
scope.files.push(element.files[i])
}
});
};
$scope.uploadFile = function() {
var fd = new FormData();
for (var i in $scope.files) {
fd.append('file', $scope.files[i])
}
$http.post('http://admin.localhost/images/patanjali', fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
})
.then(function successCallback(response) {
}, function errorCallback(response) {
});
};
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js'></script>
<input type="file" valid-file ng-model-instant id="fileToUpload" onchange="angular.element(this).scope().setFiles(this)" />
<button ng-click="uploadFile()">Upload me</button>

You can use AngularJs modules for file uploader.The modules are very useful and very comfortable.
1) https://github.com/nervgh/angular-file-upload
2) https://github.com/danialfarid/ng-file-upload

Related

how to handle errors from angular service inside controllers?

I am new to angular, I am trying to access error message from service inside my controller
here's my service looks like
admin.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(response){
console.log(response)
})
.error(function(response){
console.log(response)
});
}
}]);```
and my upload function inside controller looks like below
admin.controller('uploadCtrl', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
var uploadUrl = "/upload-url/";
fileUpload.uploadFileToUrl(file, uploadUrl)
};
});
$http.post returns a promise, and you can return that promise from the uploadFileToUrl function. Then if anyone needs to interact with the result, they can use the promise object.
Service:
admin.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
//VVVVVV---------- added return statement
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
}])
Controller
admin.controller('uploadCtrl', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
var uploadUrl = "/upload-url/";
fileUpload.uploadFileToUrl(file, uploadUrl)
//VVVVVV------------ added .then and callbacks
.then(
function (result) {
console.log('success!');
},
function (error) {
console.log('error :(');
}
)
};
});

angular.js:12416 SyntaxError: Unexpected token D in JSON at position 0

I am working with SpringBoot and AngularJS
This is the Service of My Custom Directive
this.uploadFileToUrl = function (file, csvType, uploadUrl) {
var fd = new FormData();
fd.append('csvType', csvType);
fd.append('file', file);
console.log(csvType);
console.log(fd);
$http({
url: uploadUrl,
method: 'POST',
data: fd,
headers: {'Content-Type': undefined},
transformRequest: angular.identity
}).then(function successCallback(response) {
console.log('Success: '+response.data);
return response.data;
}, function errorCallback(response) {
var a=response.toString();
42: console.log('a='+a);
console.log('Error: '+response);
});
}
Now in the Console I am getting the error :
new1.js:42 a=SyntaxError: Unexpected token D in JSON at position 0
Also I have cross-checked in the SpringBoot that it is returning a String only.
I want to return that String in my HTML.

angular and Cloudinary direct upload 400 (Bad Request)

i'm getting a 400 bad request error when trying to upload to cloudinary with the following code:
var file = /* your file */;
var cloud_name = 'your cloud_name';
var fd = new FormData();
fd.append('upload_preset', 'seller');
fd.append('file', file);
$http
.post('https://api.cloudinary.com/v1_1/' + cloud_name + '/image/upload', fd, {
headers: {
'Content-Type': application/x-www-form-urlencoded,
'X-Requested-With': 'XMLHttpRequest'
}
})
.success(function (cloudinaryResponse) {
// do stuff with cloudinary response
// cloudinaryResponse = { public_id: ..., etc. }
})
.error(function (reponse) {
});
What am I missing? Is it possible to do a Cloudinary direct upload?

How to get data from angular service to controller?

I have response from server in success , How can i send that to controller i tried then method but its throwing error then is nto defined, How can i achieve this task ?
service.js
angular.module('App').service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
console.log('service called', fd);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(resp){
console.log('success',resp);
return resp;
})
.error(function(){
});
}
}]);
controller.js
$scope.uploadFile = function(){
var file = $scope.myFile;
// console.log('file is ');
// console.dir(file);
// console.log(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl).then(function(resp){console.log(resp);
};
};
Avoid using the .success (which is deprecated anyway) in the service, and just return the promise itself.
angular.module('App')
.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
// ... other code ...
// return the $http promise itself here
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
}
}])
Then in your controller (the .catch is optional, but good to use if your $promise errors out).
$scope.uploadFile = function(){
// ... other code ...
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl)
.then(function(response) { console.log(response) })
.catch(function(error) { console.log(error) });
};
Change your code like this.
angular.module('App').service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
console.log('service called', fd);
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
}
}
$scope.uploadFile = function() {
var file = $scope.myFile;
// console.log('file is ');
// console.dir(file);
// console.log(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl)
.then(function(resp) {
console.log('Your response here', resp);
});
};
You have to return the Promise, only then you will be able to use then in the controller.
angular.module('App').service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
console.log('service called', fd);
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
}
}]);

AngularJS its sending file in a body and not in file

i have an angularjs service to send a file to a NodeJS server.
This is the code:
define([], function () {
"use strict";
var UploadService = function (API_URL, $http) {
var uploadFile = function (file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
return $http.post(API_URL + uploadUrl,fd,{
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
});
};
return {
uploadFile: uploadFile
};
};
return UploadService;
});
My problem its the file its sending in the body and not in the file, then in my nodejs when i parse with a middleware, because the request.file its undefined dont parse any file.
How can i solve this?

Categories