php - angularjs 图片上传问题?
ringa_lee
ringa_lee 2017-04-10 15:40:05
[PHP讨论组]

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

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
天蓬老师

我一般是自己写表单提交,主要原理就是利用一个隐藏的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);
                })
            });
        }
    };
})
天蓬老师

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号