Angularjs使用onLoad图像上传服务?

时间:2014-05-12 12:26:42

标签: image angularjs onload-event

我在onload图像和angular-fie-upload上遇到了一些问题。首先,我必须验证图像大小,之后我将使用以下代码将此图像上传到服务器端。我的服务看起来像那样:

 Services.factory('$uploadWrapper', ['$upload' , '$logger' , function ($upload, $logger) {
    return function (url, file, informations, onSuccess, onError, onProgress) {
        url = url || angular.noop;
        file = file || angular.noop;
        informations = informations || angular.noop;
        onSuccess = onSuccess || angular.noop;
        onError = onError || angular.noop;
        onProgress = onProgress || angular.noop;

        $upload.upload({
            url: url,
            method: 'POST',
            // headers: {'header-key': 'header-value'},
            // withCredentials: true,
            data: informations,
            file: file // or list of files: $files for html5 only
            /* set the file formData name ('Content-Desposition'). Default is 'file' */
            //fileFormDataName: myFile, //or a list of names for multiple files (html5).
            /* customize how data is added to formData. See #40#issuecomment-28612000 for sample code */
            //formDataAppender: function(formData, key, val){}
        }).progress(function (evt) {
            $logger.info(Math.min(100, parseInt(100.0 * evt.loaded / evt.total)));
            onProgress(evt);
        }).success(function (response) {
            $logger.info('POST' + url + angular.toJson(response))
            onSuccess(response);
        }).error(function (error) {
            $logger.error('POST' + url + ' ' + angular.toJson(error));
            onError(error);
        });
    }
}]);

并且对于验证过程,我将创建一个图像来获取图像的宽度和高度:

$scope.onFileSelect = function ($files) {
        $scope.loading = true;
        //$files: an array of files selected, each file has name, size, and type.
        file = $files[0];
        var img = new Image();
        img.src = _URL.createObjectURL(file);
        img.onload = function () {
            console.log(this.width + "x" + this.height);
            if (img.width > sizes.width && img.height > sizes.height) {
            $uploadWrapper(pinholeAdminServerRoutes.image.upload, file, {
                "operationType": 'channels',
                "objectId": $scope.channel.id,
                "size": 'large'
            }, function (response) {
                $scope.loading = false;
            }, function (error) {
                    $scope.errors.push(error);
                $scope.loading = false;
            });
            } else {
                $scope.imageSizeNotValid = true;
                $scope.loading = false;
            }
            console.log('finish loading');
        };
    };

但是,我的服务在onload块中无法工作。但是相同的服务可以在没有onload块的情况下工作。

1 个答案:

答案 0 :(得分:0)

我终于在$scope.$apply事件中使用onload获得了解决方案。