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


41 comments :

  1. Clean explanation sir .Thanks for article

    ReplyDelete
  2. Very good post sir thanks 4 the article

    ReplyDelete
  3. Great post!!!!!

    ReplyDelete
  4. 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
  5. Can I download whole source code in working condition? zip or something.

    ReplyDelete
  6. Thanks for the quick tutorial!

    ReplyDelete
  7. Works Perfectly. Thanks a ton :)

    ReplyDelete
  8. 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
  9. how to use this demo. i am new to angular js please help me out.

    ReplyDelete
  10. 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
  11. 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
  12. 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
  13. 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
    2. I 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
  14. $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
  15. 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
  16. No 'Access-Control-Allow-Origin' header is present on the requested resource.

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

    how to access above the data in server side?

    ReplyDelete
  18. 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
  19. 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
  20. 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
  21. can i use anything else than onchange?

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

    ReplyDelete
    Replies
    1. Please check this post
      http://www.angulartutorial.net/2017/02/show-preview-image-while-uploading.html

      Delete
  23. how do we pass the file to the server side (c# code)?

    ReplyDelete
  24. how upload multiple file with every file have different info ?

    ReplyDelete
  25. hey,
    what the type of file? is it byte or string?
    and do i need to put the factory insid a function?
    ty in advenced

    ReplyDelete
    Replies
    1. it is byte array.
      You can add code as per your standard.

      Delete
  26. I am extremely impressed along with your writing abilities and
    also 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.

    ReplyDelete
  27. Have you ever considered writing an ebook or guest authoring on other blogs?
    I 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.

    ReplyDelete