1. 程式人生 > >angularJs中上傳圖片/檔案功能:ng-file-upload

angularJs中上傳圖片/檔案功能:ng-file-upload

image-upload.html:
<button class="btn btn-default" ngf-select="selectImage($files)" ngf-pattern="'image/*'"
        ngf-multiple="true">
    選擇圖片
</button>
<span>(支援多張圖片拖拽上傳)</span>
<div class="row cropArea" style="padding: 0 15px 15px 0" ngf-drop ngf-pattern="'image/*'" ng-model="files"
     ngf-multiple="true">
    <img-crop image="files || data.defaultImage" resule-image="files"></img-crop>
    <div ngf-no-file-drop>該瀏覽器不支援拖拽上傳。</div>
    <div class="col col-xs-4 text-left" style="margin-top: 15px;" ng-repeat="image in mulImages">
        <div ng-repeat="oneImage in image">
            <img ngf-src="oneImage || data.defaultImage" class="img-responsive" 
                 style="width:200px; height: 200px; max-width:500px;"/>
        </div>
    </div>
</div>
//<img-crop></img-crop>定義了圖片可以拖拽的位置
//<img/>排列顯示上傳的多張圖片
 
style.css:
.cropArea {
    background: #E4E4E4;
    min-height: 230px;
    height: auto;
    margin: 15px;
    margin-right: 0;
}

image-upload-ctrl.js:
$scope.data = {
    file: null,
    defaultImage: commonSvc.defaultImage
};

$scope.mulImages = [];

$scope.$watch('files', function () {
    $scope.selectImage($scope.files);
});
//根據選擇的圖片來判斷 是否為一下子選擇了多張
//一下子選擇多張的資料格式為一個數組中有多個物件,而一次只選擇一張的資料格式為一個數組中有一個物件
$scope.selectImage = function (files) {
    if (!files || !files.length) {
        return;
    }
    if (files.length > 1) {
        angular.forEach(files, function (item) {
            var image = [];
            image.push(item);
            $scope.mulImages.push(image);
        })
    } else {
        $scope.mulImages.push(files);
    }
};

$scope.upload = function () {
    if (!$scope.mulImages.length) {
        return;
    }
    var url = $scope.params.url;
    var data = angular.copy($scope.params.data || {});
    data.file = $scope.mulImages;

    Upload.upload({
        url: url,
        data: data
    }).success(function (data) {
        $scope.hide(data);
        $rootScope.alert('success');
    }).error(function () {
        $rootScope.alert(‘error’);
    });

};