Saturday, 21 March 2015

File upload and sending data to backend using angular js

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

4. Angular routing

5. Loop concept in angular js

6. Filtering concept in angular js

7. Auto complete using html5


33 comments :

  1. Will this work on angular version 1.3.9?

    ReplyDelete
  2. Clean explanation sir .Thanks for article

    ReplyDelete
  3. Very good post sir thanks 4 the article

    ReplyDelete
  4. Great post!!!!!

    ReplyDelete
  5. sir $scope not defined is the error which i am getting.. why is this so?

    ReplyDelete
    Replies
    1. with out seeing the code it is tough to suggest ,check your controller scope is injected properly

      Delete
  6. Can I download whole source code in working condition? zip or something.

    ReplyDelete
  7. Thanks for the quick tutorial!

    ReplyDelete
  8. Works Perfectly. Thanks a ton :)

    ReplyDelete
  9. i 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

    ReplyDelete
    Replies
    1. you can follow the same which I explained above ,back end logic(service side) you have to write depends on which language you are using .

      Delete
  10. how to use this demo. i am new to angular js please help me out.

    ReplyDelete
  11. Thank 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.

    ReplyDelete
  12. Could 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.

    ReplyDelete
  13. I 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.

    ReplyDelete
  14. Dear Sir, I am facing server side issue.
    I 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.

    ReplyDelete
    Replies
    1. 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.

      Delete
  15. $http.post(uploadUrl, fd,

    I was to pass some parameters too with post formdata. Will you pls let me know how can i pass parameters to with formdata.

    ReplyDelete
    Replies
    1. yes ,you can refer the last example in the article

      Delete
  16. I have add following code to send extra data along with file but it is not working:

    var data ={
    token : 'ABC',
    id : '123'
    };

    fd.append("data", JSON.stringify(data));

    ReplyDelete
    Replies
    1. What is the error you are getting

      Delete
  17. No 'Access-Control-Allow-Origin' header is present on the requested resource.

    ReplyDelete
    Replies
    1. you need to handle this in service side

      Delete
  18. var data ={
    token : 'ABC',
    id : '123',
    name:mike
    };

    how to access above the data in server side?

    ReplyDelete
  19. Thank you, it is very helpful for me as well.
    But how we will access file at server side, it is not in request.body...
    I am using angularjs at server side as well

    ReplyDelete
  20. 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?

    ReplyDelete
  21. Thank 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?

    ReplyDelete
    Replies
    1. yes you need to write server side logic to get the file depends on which language you are using.

      Delete
  22. can i use anything else than onchange?

    ReplyDelete
  23. Works like charm! thank you!

    ReplyDelete
  24. how can i make a preview before upload the image? thanks in advance

    ReplyDelete