2016-05-31 48 views
0

我想上傳一個圖像以及其他類型的數據使用web api,angular JS。 我的帖子員工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; 
     }); 
    }; 
}); 

「圖像」屬性未被髮布到服務器。而是拋出null。可能與綁定有關。我不知道爲什麼圖像屬性沒有綁定到模型,而其他屬性可以。

+1

可能重複[什麼是NullReferenceException,以及如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-doi-i-修復它) – CodeCaster

+0

你可以調試你的.NET代碼嗎?我猜你的員工沒有正確綁定。嘗試添加[FromBody]屬性。而且最好在開始時檢查ModelState.IsValid –

+0

如果你想在你的Employee對象中發送一個原始字節數組,那麼這就是你的問題。但在繼續之前,您必須**調試'NullReferenceException'。 –

回答

1

我會假設你在你的html中使用一個帶有文件類型的輸入來獲取文件名。 Angular不會自動處理這些綁定,所以即使您選擇的文件顯示在瀏覽器中,它也不會更新模型。有許多指令可以解決這個缺點。

這個答案涵蓋了它非常徹底。 ng-model for <input type="file"/>

+1

,這有助於。非常感謝 –