angular不支持file控件的双向绑定怎么破!

本文介绍了在Angular中遇到文件控件(file)不支持双向绑定的问题,以及如何通过手动更新模型和使用FormData实现文件上传。示例代码包括前端HTML、控制器和上传服务,以及C#后端接口的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前端:

<form class="form-horizontal tasi-form" method="post">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" ng-click="cancel()">×</button>
            <h4 class="modal-title">{{formTitle.title}}</h4>
        </div>
        <div class="modal-body">
            <input type="file" id="file" name="file" class="btn btn-warning  pull-left" ng-src={{files[0].name}} οnchange='angular.element(this).scope().fileChanged(this)' />
        </div>
             <div class="modal-footer" style="display: block">
                <button class="btn btn-primary" ng-click="updateTplConfirm()">确定</button>
                <button class="btn btn-disabled" ng-click="cancel()">关闭</button>
            </div>
    </div>
   
</form>


控制器:

 $scope.fileChanged = function (ele) {
                $scope.files = ele.files;
                $scope.$apply(); //传播Model的变化。  
            }

            $scope.updateTplConfirm = function () {                
                //angular不支持file的ng-model双向绑定
                var fd = new FormData();
                var file = document.querySelector('input[type=file]').files[0];  
                var filename = $scope.files[0].name;  
                if (filename.length > 1 && filename)
                {  
                    var ldot = filename.lastIndexOf(".");  
                    var type = filename.substring(ldot + 1);  
                    if(type != "pdf") {  
                        toastr.warning("只能上传PDF文件!");
                    }else{
                        TplConfigService.updateTpl({}, file, function (data) {
                            if (data != null && data.state == 1) {
                                toastr.success("模板更新成功!");
                                $scope.cancel();
                            } else {
                                toastr.warning("模板更新失败!");
                            }
                        });
                    }  
                }  
            };


服务类:

 //上传文件
            uploadFile: function (url, file, par) {
                var deferred = $q.defer();
                Upload.upload({
                    //服务端接收
                    url: serviceBase + url,
                    //上传的同时带的参数
                    data: par,
                    file: file
                }).progress(function (evt) {
                    //进度条
                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                    $rootScope.progressPercentage = progressPercentage;
                    console.log('progess:' + progressPercentage + '%');
                }).success(function (data, status, headers, config) {
                    //上传成功
                    deferred.resolve(data);
                }).error(function (data, status, headers, config) {
                    //上传失败
                    console.log('error status: ' + status + data);
                });
                return deferred.promise;
            },

注入:

        commonService.service('CommonService', ['$rootScope', '$q', '$timeout', '$http', '$state', '$uibModal', 'Settings', '$window', '$localStorageUsage', '$loading', 'toastr', 'Upload', function ($rootScope, $q, $timeout, $http, $state, $uibModal, Settings, $window, $localStorageUsage,  $loading, toastr,Upload) {


注意:'$q', '$timeout', '$http' 是Upload的依赖模块。


C#后端:

   /// <summary>
        /// 更新模板
        /// </summary>    
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public MessageRs UpdateTpl()      //注意不要加入参
        {
            HttpFileCollection files = HttpContext.Current.Request.Files;
            return null;
        }


界面:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值