File Upload using AngularJS

前端 未结 29 2026
野趣味
野趣味 2020-11-21 07:24

Here is my HTML form:

29条回答
  •  死守一世寂寞
    2020-11-21 07:57

    The element does not by default work with the ng-model directive. It needs a custom directive:

    Working Demo of select-ng-files Directive that Works with ng-model1

    angular.module("app",[]);
    
    angular.module("app").directive("selectNgFiles", function() {
      return {
        require: "ngModel",
        link: function postLink(scope,elem,attrs,ngModel) {
          elem.on("change", function(e) {
            var files = elem[0].files;
            ngModel.$setViewValue(files);
          })
        }
      }
    });
    
      
        

    AngularJS Input `type=file` Demo

    Files

    {{file.name}}


    $http.post from a FileList

    $scope.upload = function(url, fileList) {
        var config = { headers: { 'Content-Type': undefined },
                       transformResponse: angular.identity
                     };
        var promises = fileList.map(function(file) {
            return $http.post(url, file, config);
        });
        return $q.all(promises);
    };
    

    When sending a POST with a File object, it is important to set 'Content-Type': undefined. The XHR send method will then detect the File object and automatically set the content type.

提交回复
热议问题