Here we are going to discuss about uploading a file and sending to backend.
Html
<form name="upload" class="form" data-ng-submit="addFile()">
<input type="file" name="file" multiple
onchange="angular.element(this).scope().uploadedFile(this)" />
<button type="submit">Upload </button>
</form>
Controller
$scope.uploadedFile = function(element) {
$scope.$apply(function($scope) {
$scope.files = element.files;
});
}
Here uploadservice is nothing but my factory file .AS per MVC standard it would be good handling all data manipulation in factory file or service file.
$scope.addFile = function() {
UploadService.uploadfile($scope.files,
function( msg ) // success
{
console.log('uploaded');
},
function( msg ) // error
{
console.log('error');
});
}
Factory file
uploadfile : function(files,success,error){
var url = 'your web service url';
for ( var i = 0; i < files.length; i++)
{
var fd = new FormData();
fd.append("file", files[i]);
$http.post(url, fd, {
withCredentials : false,
headers : {
'Content-Type' : undefined
},
transformRequest : angular.identity
})
.success(function(data)
{
console.log(data);
})
.error(function(data)
{
console.log(data);
});
}
}
Your file is successfully uploaded
Upload a file and send data and file to backend
If you want to send data along with file upload you can try below code .There is a slight change while sending data
uploadfile : function( files,success, error )
{
var fd = new FormData();
var url = 'your web service url';
angular.forEach(files,function(file){
fd.append('file',file);
});
//sample data
var data ={
name : name,
type : type
};
fd.append("data", JSON.stringify(data));
$http.post(url, fd, {
withCredentials : false,
headers : {
'Content-Type' : undefined
},
transformRequest : angular.identity
})
.success(function(data)
{
console.log(data);
})
.error(function(data)
{
console.log(data);
});
},
Related Posts
1. How to download file from backend to UI
2. Communicate with controllers in angular js
3. Rating Stars using angular js Directive concept
6. Filtering concept in angular js
Clean explanation sir .Thanks for article
ReplyDeleteVery good post sir thanks 4 the article
ReplyDeleteGreat post!!!!!
ReplyDeletesir $scope not defined is the error which i am getting.. why is this so?
ReplyDeletewith out seeing the code it is tough to suggest ,check your controller scope is injected properly
DeleteCan I download whole source code in working condition? zip or something.
ReplyDeleteI dont have any zip right now
DeleteThanks for the quick tutorial!
ReplyDeleteWorks Perfectly. Thanks a ton :)
ReplyDeletei m new new to angular js. i wnt to make image uploading and insert into db.i cnt understand how to use this demo.. plese help me out
ReplyDeleteyou can follow the same which I explained above ,back end logic(service side) you have to write depends on which language you are using .
Deletehow to use this demo. i am new to angular js please help me out.
ReplyDeleteThank you sir its good explanation, Actually I am using WCF service so can you suggest me for the server side code, how to create method to upload file in folder.
ReplyDeleteCould you please post the server side code as well. I need to upload 500MB file from browser and need to save to desire location from server side. I am using nodejs at server side. Right now if I am uploading large file it give me error saying "Payload content length greater than maximum allowed: 1048576". How could we fix this. Do it need stream the file at server side. How could I do that. Thank you.
ReplyDeleteI agree, it would be really helpful if you showed how to pass uploaded file to back end method as well. I am trying to make this work with C# back end code, but how do I pass the file uploaded to the C# method? Thanks.
ReplyDeleteDear Sir, I am facing server side issue.
ReplyDeleteI am using WCF restful API service then please tell me how to define the service method in Interface to receive this Formdata?
I am stuck in this problem since last 5 days without any solution.
Here what I Tried :-
1. void audioFileUpload(string MyFile, string[] MyFilebyte);
2. void audioFileUpload(NameValue MyFile);
3. void audioFileUpload(System.Web.HttpRequest req, System.Web.HttpResponse res);
4. void audioFileUpload(System.Web.HttpPostedFile fd);
But every time I am getting null value not file.
Please guide me please.
were you able to fix this issue. I am having the same issue. File value is always null. If you have the server side code, could you please post it here.
DeleteI have tested this approach with java and .net and it worked fine, here basically I wont be sharing service side codes since this blog is related to UI stuffs.
Delete$http.post(uploadUrl, fd,
ReplyDeleteI was to pass some parameters too with post formdata. Will you pls let me know how can i pass parameters to with formdata.
yes ,you can refer the last example in the article
DeleteI have add following code to send extra data along with file but it is not working:
ReplyDeletevar data ={
token : 'ABC',
id : '123'
};
fd.append("data", JSON.stringify(data));
What is the error you are getting
DeleteNo 'Access-Control-Allow-Origin' header is present on the requested resource.
ReplyDeleteyou need to handle this in service side
DeleteThank you very much
ReplyDeletevar data ={
ReplyDeletetoken : 'ABC',
id : '123',
name:mike
};
how to access above the data in server side?
Thank you, it is very helpful for me as well.
ReplyDeleteBut how we will access file at server side, it is not in request.body...
I am using angularjs at server side as well
I use the same method. But when i try var_dump($_POST) on backend, it seems NULL. Do I have to make any changes on backend to catch the data in POST?
ReplyDeleteThank you for tutorial. I use the same method, I can send the image file and at server side var_dump($_FILES) shows the result. But var_dump($_POST) is NULL. I checked everything but no solution. Do I have to make any changes at server side to catch the POST value?
ReplyDeleteyes you need to write server side logic to get the file depends on which language you are using.
Deletecan i use anything else than onchange?
ReplyDeleteWorks like charm! thank you!
ReplyDeletehow can i make a preview before upload the image? thanks in advance
ReplyDeletePlease check this post
Deletehttp://www.angulartutorial.net/2017/02/show-preview-image-while-uploading.html
how do we pass the file to the server side (c# code)?
ReplyDeletehow upload multiple file with every file have different info ?
ReplyDeletehey,
ReplyDeletewhat the type of file? is it byte or string?
and do i need to put the factory insid a function?
ty in advenced
it is byte array.
DeleteYou can add code as per your standard.
thank you!!!
DeleteI am extremely impressed along with your writing abilities and
ReplyDeletealso with the format on your blog. Is that this a paid topic or did you modify it yourself?
Either way stay up the excellent quality writing, it's rare to look a nice weblog like this one nowadays.
Have you ever considered writing an ebook or guest authoring on other blogs?
ReplyDeleteI have a blog based upon on the same information you discuss and would really like to have you share some stories/information. I know
my viewers would value your work. If you are even remotely interested, feel free to send me
an email.