【问题标题】:why is "Image" in my model null?为什么我的模型中的“图像”为空?
【发布时间】:2016-09-29 17:04:49
【问题描述】:

我正在尝试使用 web api、angular JS 上传图像以及其他类型的数据。 我的 POST 员工 API 控制器操作是:

[ResponseType(typeof(Employee))]
public async Task<IHttpActionResult> PostEmployee(Employee employee)
{
    byte[] data = new byte[employee.Image.ContentLength];
    employee.Image.InputStream.Read(data, 0, employee.Image.ContentLength);
    employee.Picture = data;
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.Employees.Add(employee);
    await db.SaveChangesAsync();

    return CreatedAtRoute("DefaultApi", new { id = employee.ID }, employee);
}

服务 JavaScript 是:

app.service('Service', function ($http) {
    this.getEmployees = function () {
        return $http.ger("/api/EmployeeApi");
    }

    this.post = function (Employee) {
        var request = $http({
            method: "post",
            url: "/api/EmployeeApi/PostEmployee",
            data: Employee,
            headers: {
                'Content-Type' : 'application/json'
            }
        });
        return request;
    };
});

我用于将员工发布到服务器的“AddEmployee”控制器是

app.controller('AddEmployee', function ($scope, Service) {
    $scope.ID = 1;
    $scope.save = function () {
        var Employee = {
            ID: $scope.ID,
            Name: $scope.Name,
            Experience: $scope.Experience,
            EmployerName: $scope.EmployerName,
            Image:$scope.Image
        };
        var Post = Service.post(Employee);
        Post.then(function (pl) {
            alert("Student Saved Successfully.");
        },
        function (errorPl) {
            $scope.error = 'failure loading Student', errorPl;
        });
    };
});

“图像”属性未发布到服务器。而是抛出空值。可能是绑定问题。我不确定为什么图像属性没有绑定到模型,而其他属性可以。

【问题讨论】:

  • 你能调试你的 .NET 代码吗?我猜你的 Employee 没有正确绑定。尝试添加 [FromBody] 属性。而且最好在开头检查ModelState.IsValid
  • 如果您尝试在 Employee 对象中发送原始字节数组,那就是您的问题。但在继续之前,您必须调试NullReferenceException
  • @CodeCaster ,这不是您提到的问题的重复。图片未发布到服务器,它正在抛出 null 。
  • @RomanKoliada ,我尝试调试。 “图像”抛出空值。这就是我出错的原因。

标签: angularjs asp.net-web-api image-uploading


【解决方案1】:

我假设您在 html 中使用带有文件类型的输入来获取文件名。 Angular 不会自动处理这些绑定,因此即使您选择的文件显示在浏览器中,它也不会更新模型。有许多指令可以解决这个缺点。

这个答案涵盖了它非常彻底。 ng-model for <input type="file"/>

【讨论】:

  • 这有帮助。非常感谢
猜你喜欢
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
相关资源
最近更新 更多