首页 > angularjs 图片上传问题?

angularjs 图片上传问题?

如何实现angularjs图片上传,并获取图片路径


https://github.com/danialfarid/ng-file-upload


我一般是自己写表单提交,主要原理就是利用一个隐藏的input,然后自己写指令到input上,代码可参照如下:

function checkImgType(file) {
    var type = file.name.split(".");
    if (type[type.length - 1] != 'png' && type[type.length - 1] != 'jpg' && type[type.length - 1] != 'jpeg') {
        return false;
    }
    return true;
};
 $scope.upload = function(name, imgUrl) {
        var fileObj = document.getElementById(name).files[0];
        if (fileObj) {
            $scope.imgloading[imgUrl] = true;
        }
        if (!checkImgType(fileObj)) {
            alert("图片格式错误,只支持png,jpg,jpeg格式");
            return;
        }
        var form = new FormData();
        form.append("file", fileObj);
        var xhr = new XMLHttpRequest();
        xhr.open("POST",httpBase+  "upload", true);

        function callback() {
            if (xhr.readyState == 4) {
                $timeout(function() {
                    var data = angular.fromJson(xhr.responseText);
                   
                    $scope.$apply(function() {
                        $scope.goods[name] = data.statusMessage;
                    });
                }, 3000);
            }
        };
        xhr.onreadystatechange = callback;
        xhr.send(form);
    };

html

<label for="commodityImg">
            <input class="hide" type="file" id="commodityImg" ng-model="commodityImg" lt-file    file-Fn="upload('commodityImg','commodityImg')" accept=" image/png" />

</label

补充下指令

.directive("ltFile", function() {
    return {
        restrict: 'AE',
        link: function(scope, elm, attr, ngModelCtrl) {
            elm.bind('change', function(newValue,oldValue) {
                scope.$apply(function() {
                    eval("scope." + attr.fileFn);
                })
            });
        }
    };
})
【热门文章】
【热门文章】