Image upload using rest api in Angularjs - javascript

I have to upload image using rest api for successfull upload will get the response of file folder destination ex: D:/ddd/download,I am not able to upload image, below is my code given suggest me any corrections. while uploading image i have to give parameter name as fileData.
api ex: http://somelink and parameter for post is fileData
Html code
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
my service and directive
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
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(){
});
}
}]);
my controller file
$scope.uploadFile = function(){
var data={
'fileData':$scope.myFile
}
var uploadUrl = "http://";
fileUpload.uploadFileToUrl(data, uploadUrl).success(function(response) {
$scope.fileName=response;
})
};

Please check on this...
Controller:
$scope.uploadFile = function () {
var file = $scope.myFile;
console.log(file);
if(file.type==='image/jpeg' || file.type==='image/jpg' || file.type==='image/png' ){
var uploadUrl = "http://";
fileUpload.uploadFileToUrl(file, uploadUrl);
angular.element('input[type="file"]').val(null);
}else{
$scope.errorMessage='File Type Error';
}
};
Service:
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, url) {
var uploadUrl = url;
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function () {
console.log("Image Save");
})
.error(function () {
});
};
}]);

You want to pass a the file itself to the formdata object
fileUpload.uploadFileToUrl($scope.myFile, uploadUrl).success(function(response) {
$scope.fileName=response;
})
and set the first parameter of append as fileData
fd.append('fileData', file);

Hi friends now the image upload is working, i have removed service and done changes to my controller by adding below code.
var file = $scope.myFile;
var uploadUrl = "http://";
var fd = new FormData();
fd.append('fileData', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(response){
$rootScope.fileValue = response;
})

Related

How can I make my .factory return the result on a promise (.then)

I have this factory:
I'm basically trying to get a file to my server. And when I finish uploading it, I want it to return an answer.
.factory('fileUpload', function($http)
{
var ofileUpload = {};
ofileUpload.uploadFileToUrl = function(file, uploadUrl)
{
var fd = new FormData();
fd.append('file', file);
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
,function(){
ofileUpload.answer="success";
ofileUpload.respuesta;
},function(){
ofileUpload.answer="failure";
ofileUpload.answer;
};
}
return ofileUpload;
})
In my controller I am trying to do this:
//I am executting this:
fileUpload.uploadFileToUrl(file, uploadUrl).then(function(){
console.log(fileUpload.answer)
});
but this error appears to me.
TypeError: fileUpload.uploadFileToUrl(...).then is not a function
How can I have my .factory return the response on a promise to receive the value returned (ofileUpload.answer) in my controller?
I solved that. thank you!
.factory('fileUpload', function($http)
{
var ofileUpload = {};
ofileUpload.uploadFileToUrl = function(file, uploadUrl)
{
var fd = new FormData();
fd.append('file', file);
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function(data) {
ofileUpload.answer="success";
},function(response) {
ofileUpload.answer="failure";
});
}
return ofileUpload;
})

Service showing undefined in angular

I have wrote one service which will upload image to server and I am using that service from controller but on call to service showing that undefined function which is defined in service. and error is something like this "Cannot read property 'uploadFileToUrl' of undefined"
here is my code
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file,clientid, uploadUrl){
var fd = new FormData();
fd.append('file', file);
fd.append('id', clientid);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(response){
console.log(response)
})
.error(function(){
});
}
}]);
and here i am calling this service
app.controller('settingsCtrl', ['$scope','apiCall','$filter', function($scope,apiCall,$filter,fileUpload){
$scope.saveStudioBranch = function(){
studio();
admin();
branch();
}
function studio(){
var studio_json = {"session_id":session_id,"u":[{"col":"studio","val":$scope.studioDetails.studio},{"col":"type","val":$scope.studioDetails.type}],"filter":[["id","=","1"]],"table":"studio"};
apiCall.callEndpoint(studio_json,"settingRoute.php","update",json_header).then(function(response){
if(response.data.error == 0){
if($scope.inst_logo != undefined ){
var uploadUrl = "https://papa.fit/routes/registrationRoute.php?action=instLogo";
-->> fileUpload.uploadFileToUrl($scope.inst_logo,session.client_id,uploadUrl);
}
}
else
show_snack(response.data.message);
});
}
});
I have added a arrow where I am calling service from
the error is in the injection
app.controller('settingsCtrl', ['$scope','apiCall','$filter',
function($scope, apiCall, $filter, fileUpload){
you forgot to add fileUpload service inside the list of parameters
app.controller('settingsCtrl', ['$scope','apiCall','$filter', 'fileUpload',
function($scope, apiCall, $filter, fileUpload){
You must return your service, or else it would be undefined
function uploadFileToUrlSrv($http) {
var service = {};
service.uploadFileToUrl = function(file,clientid, uploadUrl){
var fd = new FormData();
fd.append('file', file);
fd.append('id', clientid);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(response){
console.log(response)
})
.error(function(){
});
}
return service;
}

angular error: $http.post is not a function

I am trying to post file on my server as soon as it will get attached with directve so I did api call but I got this error while doing. I don't know where am i going wrong
here is my code
app.directive('fileModel',fileupload);
fileupload.$inject = ['$http','$parse'];
function fileupload ($http,$parse) {
return {
restrict: 'A',
link: function(scope, element, attrs,$http) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function($http){
modelSetter(scope, element[0].files[0]);
var fd = new FormData();
fd.append('file', element[0].files[0]);
fd.append('id', user_id);
var uploadUrl = "https://******/routes/contactRoute.php?action=upload";
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.log(response)
});
});
});
}
};
}
Remove $http from link function. it is not needed
app.directive('fileModel',fileupload);
fileupload.$inject = ['$http','$parse'];
function fileupload ($http,$parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function($http){
modelSetter(scope, element[0].files[0]);
var fd = new FormData();
fd.append('file', element[0].files[0]);
fd.append('id', user_id);
var uploadUrl = "https://******/routes/contactRoute.php?action=upload";
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.log(response)
});
});
});
}
};
}
Edit 1: You also need to remove $http from $apply callback. You don't need to pass $http to any other internal function. It has been already injected and available for all other internal methods.
scope.$apply(function(){}

http get and post Angular

Hello here's my json "names" :
[
{
"file": "file1.zip",
"date": "12-03-2016",
},
{
"file": "file2.zip",
"date": "24-06-2016",
},
{
"file": "file3.zip",
"date": "02-12-2016",
}]
My javascript file:
var app = angular.module('app', []);
app.service('service', function($http, $q){
var deferred = $q.defer();
$http.get('newapi.json').then(function(data){
deferred.resolve(data);
});
this.getNames = function(){
return deferred.promise;
}
});
app.controller('FirstCtrl', function($scope, service){
var promise = service.getNames();
promise.then(function(data){
$scope.names = data.data;
$scope.namesplit = $scope.names;
$scope.namesplit.map(function(item) {
item.time = new Date(item.date * 1000);
});
console.log($scope.namesplit);
});
});
and HTML :
<tr ng-repeat="name in names">
<td>{{name.file}}</td>
<td>{{name.date}}</td>
<td><button>POST</button></td>
</tr>
Well i have a table and what i need is when i click on button, the "file" post to serwer. I know i must use $http.post but i don't know how to do it.
So Simple
Html
<button ng-click="post()">Click Me</button>
Controller
$scope.post=function(){
$http.post(URL HERE, data-here, {
})
.then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
}).
catch(function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
});
}
For upload a file using $http.post() function you have to set some additional parameters like headers and and transformRequest.
Here a simple example:
$scope.postToServer = function(){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
Note: in this example the file var is the content of the file located on client file system and the uploadUrl is the URL of your service that handle the request.

AngularJs file upload showing error

I am using simple file upload code. Its showing error :
Here is my code :
<input type="file" name="student_image" onchange="angular.element(this).scope().uploadFile(this.files)" ng-model="formData.studentImage" id="student_image">
$scope.uploadFile = function (files) {
var form_data = new FormData();
form_data.append("file", files[0]);
$http.post('process.php', form_data, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data) {
if (data == "failed") {
// if not successful, bind errors to error variables
$scope.errorFinal = "Failed";
} else {
$scope.formData.image_name = data;
}
}).error('failed');
};
Try This
angular.element(this).scope().uploadFile(this);
.
<input type="file" name="student_image" onchange="angular.element(this).scope().uploadFile(this)" ng-model="formData.studentImage" id="student_image">
JS
$scope.uploadFile = function(data){
console.log(data.files[0]);
};

Categories

Resources