File Upload using AngularJS

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

Here is my HTML form:

29条回答
  •  难免孤独
    2020-11-21 08:15

    Easy with a directive

    Html:

    
    

    JS:

    app.directive('fileUpload', function () {
    return {
        scope: true,        //create a new scope
        link: function (scope, el, attrs) {
            el.bind('change', function (event) {
                var files = event.target.files;
                //iterate files since 'multiple' may be specified on the element
                for (var i = 0;i

    In the directive we ensure a new scope is created and then listen for changes made to the file input element. When changes are detected with emit an event to all ancestor scopes (upward) with the file object as a parameter.

    In your controller:

    $scope.files = [];
    
    //listen for the file selected event
    $scope.$on("fileSelected", function (event, args) {
        $scope.$apply(function () {            
            //add the file object to the scope's files collection
            $scope.files.push(args.file);
        });
    });
    

    Then in your ajax call:

    data: { model: $scope.model, files: $scope.files }
    

    http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/

提交回复
热议问题