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

来源:互联网 发布:网络作品版权出售 编辑:程序博客网 时间:2024/06/06 11:36

转自: 出处 (上传)

转自: 出处 (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>


阅读全文
0 0