使用Asp.net Web api 2上传带有其他数据的图像文件?

时间:2016-02-05 22:38:16

标签: asp.net angularjs upload asp.net-web-api2 multipartform-data

我使用AngularJS和ASP.NET Web API构建了一个Web应用程序。

在注册用户的视图中,我有一个输入文件来上传用户图像和其他个人信息,如电话号码和全名。我想将一个对象中的所有这些信息发送到Web API。

1。 Web API动作注册:

    public HttpResponseMessage Register(RegisterBindingModel model)
    {
        try
        {
            //we test if all data are correct
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

2。 RegisterBindingModel:

    Public class RegisterBindingModel
{
        public string FullName {get;set;}
        public string PhoneNumber {get;set;}
        public HttpPostedFileBase file { get; set; } 

}

3。 AngularJs查看:

<form role="form" name="addForm" enctype="multipart/form-data" novalidate>

        <!--Personal Informations-->
        <div class="row">
            <div class="col-xs-12 text-center" >
                <div class="form-group">
                    <div class="btn btn-default btn-file">
                        <i class="fa fa-plus"></i> select logo
                        <input type="file"
                               name="file"
                           ng-model="vm.registration.file" />

                    </div>
                            <input type="text"
                               name="FullName"
                           ng-model="vm.registration.FullName" />
                       <input type="text"
                               name="PhoneNumber"
                           ng-model="vm.registration.PhoneNumber" />
                    <div>
                        <button ng-click="vm.register()">Save</button>
                    </div>
                </div>

4。角度控制器:

vm.register = function () {
        authService.saveRegistration(vm.registration).then(
            function (results) {
            vm.cancel();
        },
         function (error) {


         });
    };    

5.Angular authService:

var _saveRegistration = function (registration) {

        return $http
                 .post(serviceBase + 'api/account/register', registration)
                 .then(function (response) {
            return response;
        });

    };

即使我在Web API操作注册表中选择了一个文件,我model.file等于null,但其他数据如FullName和PhoneNumber我得到了正确的值!。

有人可以帮我吗?

0 个答案:

没有答案
相关问题