如何通过angularjs和php中的web服务上传图像

时间:2015-04-08 09:51:08

标签: php angularjs web-services

我正在使用AngularJS进行移动应用程序的webservice,我必须上传图像,我已经在Web应用程序中完成了图像上传,但是如何使用AngularJS和PHP在webservice上传图像?我已经花了10多个小时,现在我需要帮助很严重。

贝娄是我的代码。

var app = angular.module('myApp', ['ngRoute', 'ngFileUpload']);
app.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function (file, uploadUrl) {
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
                .success(function () {
                })
                .error(function () {
                });
    }
}]);
app.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function () {
                scope.$apply(function () {
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);
app.config(['$routeProvider',
function ($routeProvider) {
    $routeProvider

            .when('/signup', {
                title: 'signup',
                templateUrl: 'partials/registration_form.html',
//                    controller: 'signupCtrl'
            })
            ;
}])
    .run(function ($rootScope, $location, Data, $templateCache) {
        $rootScope.$on("$viewContentLoaded", function () {
            $templateCache.removeAll();
        });
    });



app.controller('signupCtrl', ['$scope', 'Data', '$upload', '$http', 'fileUpload', function ($scope, Data, $upload, $http, fileUpload) {

    $scope.postForm = function (file, user) {

        Data.post('signup.php', {obj: user}).then(function (results) {
            //            Data.post('signup.php', {obj: $location.search()}).then(function (results) {

            if (results.status == "0") {
                $scope.formUpload = true;
                if (file != null) {
                    $scope.uploadFile(file);
                }
            }
            $scope.result = results;
        });

        //uploadUsing$upload(file, user);


    }
    $scope.uploadFile = function (file) {
        var uploadUrl = "upload/user";
        fileUpload.uploadFileToUrl(file, uploadUrl);
    };
}]);

我创建了一个演示表来测试图片上传

<div ng-controller="signupCtrl">
<form name="userForm" ng-submit="postForm(vImage,obj)" role="form">
    <table>
        <tr>
            <td>First Name</td>
            <td><input type="text" ng-model="obj.vFirst"></td>
        </tr>
        <tr>
            <td>Last Name</td>
            <td><input type="text" ng-model="obj.vLast"></td>
        </tr>
        <tr>
            <td>Email</td>
            <td><input type="text" ng-model="obj.vEmail"></td>
        </tr>
        <tr>
            <td>vPassword</td>
            <td><input type="text" ng-model="obj.vPassword"></td>
        </tr>
        <tr>
            <td>eGender</td>
            <td>Male: <input type="radio" ng-model="obj.eGender" name="eGender" value="Male"> Female: <input type="radio" ng-model="obj.eGender" name="eGender" value="Female"></td>
        </tr>
        <tr>
            <td>Image</td>
            <td><input type="file" file-model="vImage" name="vImage" accept="image/*"></td>
        </tr>
        <tr>
            <td>Dob</td>
            <td><input type="text" ng-model="obj.vDob"></td>
        </tr>
        <tr>
            <td>Phone</td>
            <td><input type="text" ng-model="obj.vPhone"></td>
        </tr>
        <tr>
            <td>Address</td>
            <td><textarea type="text" ng-model="obj.tAddress">
</textarea></td>
        </tr>
        <tr>
            <td>City</td>
            <td><input type="text" ng-model="obj.vCity"></td>
        </tr>
        <tr>
            <td>Country</td>
            <td><input type="text" ng-model="obj.vCountry"></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="Submit Form">
</td>
        </tr>
    </table>
</form>
</div>

我尝试了这个和许多其他解决方案,但没有运气...... :(

https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

如果我创建了一个不正确的方法,请告诉我创建webservice的正确方法。

1 个答案:

答案 0 :(得分:0)

在我正在进行的项目中,我使用过这个组件: https://github.com/nervgh/angular-file-upload我可以诚实地说它做得好。

以下是一个工作示例http://nervgh.github.io/pages/angular-file-upload/examples/simple/,这是一个使用 PHP 作为后端https://github.com/nervgh/angular-file-upload/tree/master/examples/simple

的工作示例

您的angularjs控制器将只包含FileUplaoder

的实例
$scope.uploader = new FileUploader({
   url: 'upload.php'
});

您的HTML将如下所示

<input id="image-upload-input" class="hide" name="image" nv-file-select="" uploader="uploader" type="file" />

一旦你从弹出窗口中选择一个文件,然后点击确定,上传就会开始了。如果你想提供一个加载栏或其他东西,这个插件还为你提供下载的每一步的钩子

示例:

uploader.onAfterAddingFile = function() {
    scope.uploading = true;
    progressbar.width('0%');
};
uploader.onProgressItem = function(fileitem, progress) {
    var progressBar = element.find('.progressbar');

    progressBar.width(progress + '%');
    scope.uploading = fileitem.isUploading;
};
uploader.onSuccessItem = function(fileitem) {
    scope.uploading = fileitem.isUploading;

    scope.$broadcast('image::uploaded', 'test');
};
uploader.onCompleteItem = function(fileitem) {
    scope.uploading = fileitem.isUploading;
};

您还可以通过将文件添加到队列来控制文件,并仅在表单提交上触发上传。您可以将autoupload属性设置为false,如下所示:

$scope.uploader = new FileUploader({
  url: imageModel.getUploadURL(),
  alias: 'image',
  autoUpload: false
});

并手动触发上传:

$scope.uploader.uploadAll();

API参考:https://github.com/nervgh/angular-file-upload/wiki/Module-API

希望这有帮助。