【问题标题】:Upload File and Send Data AngularJS + WebAPI上传文件和发送数据 AngularJS + WebAPI
【发布时间】:2015-08-27 13:03:27
【问题描述】:

我需要使用 AngularJS(也适用于 IE8)执行文件上传并将表单数据发送到 WebApi 控制器。

我的表单定义为

<form name="sendForm" ng-submit="submitForm()">
        <input type="text" name="fname" placeholder="First name" ng-model="form.firstname">
        <br>
        <input type="text" name="lname" placeholder="Last name" ng-model="form.lastname">
        <br>
        <input type="text" name="email" placeholder="Email" ng-model="form.email">
        <br>
        <input type="file" ng-model="form.file_idea" id="file_profile"><br />
        <br>
        <input type="submit" value="Submit">
    </form>

我的 Angular 控制器方法是:

$scope.submitForm = function ()
{
    formData = $scope.form;

    var formObjectForWebApi =
        {
            Username: $scope.form.firstname,
            Lastname: $scope.form.lastname,
            Email: $scope.form.email,
        };

    $masterContext.SendForm(formObjectForWebApi).then(function (res)
    {
    });
}

我的主上下文定义为

var MasterContext = angular.module("MasterContext", []); MasterContext.service("MasterContextService", ["$resource",

function ($resource)
{
    var service = {};

    service.SendForm= function (form)
    {
        var webapiresource = $resource('/api/formcontroller/sendform');

        return webapiresource.save(form).$promise.
                then(function (res)
                {
                    return res;
                },
                function error(res)
                {
                    return res;
                });
    };

    return service;
}]);

我的 Web Api 接收数据为

[Route("api/formcontroller/sendform")]
[HttpPost]
public IHttpActionResult SendForm(MyForm form)
{
   .
   .
   .
   .
   .

如果我检查当前请求,我无法找到用户想要上传的文件。我该如何解决我的情况?

【问题讨论】:

    标签: angularjs file-upload asp.net-web-api


    【解决方案1】:

    编写以下代码以在您的方法中获取文件。

    System.Web.HttpFileCollection httpRequest = System.Web.HttpContext.Current.Request.Files;
    for (int i= 0; i <= httpRequest.Count - 1; i++) {
        System.Web.HttpPostedFile postedfile= httpRequest[i];<br/>
        if (postedfile.ContentLength > 0) {
            'logic'
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 2016-01-04
      • 2015-05-22
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多