AngularJS在单个请求中上传多个文件

时间:2020-02-06 08:25:42

标签: angularjs

<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();
}
}

是否可以将文件存储在数组中?我应该为ng-model设置什么值?

1 个答案:

答案 0 :(得分:1)

检查以下代码。

注意事项:

  1. 您需要附加onchange事件并使用angular.element(this).scope()获取范围
  2. 您需要将代码包装在$scope.$apply中。如果要在视图上显示文件列表,这是必需的。这是必要的,因为files数组没有被角度跟踪,因为它没有分配为ng-model
  3. 'Content-Type': undefined中需要
  4. 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>