angularjs上传 和 <input type="file">与ng-model 的玩法

转自: 出处 (上传)

转自: 出处 (input 和 ng-model如何联系)


其中定义 file 这个 ng 指令是核心内容


<body ng-controller="con">
    <h3>项目信息</h3>
    <form>
        文件 <input type="file" name="upload_file" file="upload_file"><br>
        <input type="button" ng-click="sub()" value="保存">
    </form>
</body>
<script type="text/javascript">
    angular.module("app",[])
        # 构建 file 指令必须有
        .directive('file', function () {
            return {
                scope: {
                    file: '='
                },
                link: function (scope, el, attrs) {
                    el.bind('change', function (event) {
                        var file = event.target.files;
                        scope.file = file ? file : undefined;
                        scope.$apply();
                    });
                }
            };
        })
        .controller("con",function($scope,$http){
            $scope.sub = function(){
                tmp_file = $scope.upload_file
                $http({
                    headers : {
                        'content-type': 'multipart/form-data',
                    },
                    method: "POST",
                    url: "yourUrl",
                    data : tmp_file,
                    # ransformRequest 函数是必须有
                    transformRequest: function (data, headersGetter) {
                        var formData = new FormData();
                        angular.forEach(data, function (value, key) {
                            formData.append(key, value);
                        });


                        var headers = headersGetter();
                        delete headers['Content-Type'];


                        return formData;
                    },
                }).then(function(response){
                    console.log(response);
                },function(response){
                    console.log(response);
                });
            }
        })
</script>


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值