Srikanth Gowda
Srikanth Gowda

Reputation: 6541

Angularjs multiple file upload in single request

<input type="file" ng-model="item.files" ng-change="item.onSelectFile()"/>

function MyController($scope, httpSrvc){
function Item(){
this.name = "";
this.files = [];
this.onSelectFile = function(file){
if(this.files.length < 3){
this.files.push(file);
}
}
this.onSubmit = function(){
let formData = new FormData();
formData.append("name",this.name);
for(let i = 0 ; i < this.files.length ; i++){
formData.append(`page_${i+1}`,this.files[i]);
}
httpSrvc.post(url,formData)
.then(function(res){console.log(res)})
.catch(function(err){console.log(err)})
}
}


function init(){
$scope.item = new Item();
}
}

is it possible to store file in a array? what value should I set to ng-model?

Upvotes: 0

Views: 59

Answers (1)

Aditya Bhave
Aditya Bhave

Reputation: 1028

Check following code.

Points to note :

  1. You need to attach onchange event and get the scope with angular.element(this).scope()
  2. You need to wrap your code inside $scope.$apply. This is required if you want to display the list of files on the view. This is necessary since the files array is not tracked by angular since it is not assigned as ng-model.
  3. 'Content-Type': undefined is required in the http headers

angular.module('myApp', []).controller('MyController', ['$scope', '$http',
  function MyController($scope, $http) {
    function Item() {
      this.name = "";
      this.files = [];

      this.onSelectFile = function(event) {
        $scope.$apply(() => {
          let file = event.target.files[0];

          if (this.files.length < 3) {
            this.files.push(file);
          }
        });
      }

      this.onSubmit = function() {

        let formData = new FormData();
        formData.append("name", this.name);
        for (let i = 0; i < this.files.length; i++) {
          formData.append(`page_${i+1}`, this.files[i]);
        }

        let url = "www.google.com";

        let request = {
          method: 'POST',
          url: url,
          data: formData,
          headers: {
            'Content-Type': undefined
          }
        };


        $http(request)
          .then(function(res) {
            console.log(res)
          })
          .catch(function(err) {
            console.log(err)
          })
      }
    }


    function init() {
      $scope.item = new Item();
    }

    init();

    document.querySelector('input[type="file"]').addEventListener('change', (event) => $scope.item.onSelectFile(event));
  }
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
  <input type="file" ng-model="item.file" />

  <ul>
    <li ng-repeat="file in item.files">
      {{ file.name }}
    </li>
  </ul>

  <input type="button" value="Submit" ng-click="item.onSubmit()">
</div>

Upvotes: 1

Related Questions