2016-04-29 25 views
1

我開始使用AngularJS和typescript,我試圖做一個與WebAPI上的頁面進行通信的表單上傳。 但是我仍然無法理解語法的角度以及指令和控制器。上傳到AngularJS + Typescript的WebApi

我看到很多使用AngularJS和純JavaScript的例子,但是不能將javascript代碼轉換爲typescript。我正在使用ng-file-upload庫。我是一個小白:(

HTML:

<html> 
<body> 
    <form action="#" method="post" ng-submit="vm.send($event)" class=""> 
    <p> 
     <label>Name</label> 
     <input type="text" 
      name="Name" 
      required="required" 
      ng-model="vm.Name"/> 
    </p> 
    <p> 
     <label>Image:</label> 
     <input type="file" 
      ngf-select name="file"  
      accept="image/*" ngf-max-size="2MB" 
      ng-model="vm.Image"/> 
    </p> 
    <p ng-show="vm.Image"> 
     <label>Preview:</label> 
     <img ngf-thumbnail="vm.Image" class="thumb"><button ng-click="vm.Image = null" ng-show="vm.Image">Remove</button> 
    </p> 
    <p> 
     <button type="reset" ng-click="vm.quit()">Quit</button> 
     <button>Send</button> 
    </p> 
    </form> 
</body> 
</html> 

打字稿:

module MyFramework.Controllers.upload { 
    export class UploadController { 
     public vm: any; 
     public window: any; 

     public static $inject = ["framework", "$http", "$scope", "Upload", "$timeout"]; 
     constructor(framework, private $http, private $scope, private $Upload, private $timeout) {} 

     send(event) { 
      event.preventDefault(); 
      this.$http.post("api/upload", this.vm) 
       .success((message) => { 
        alert("Ok");; 
       }) 
       .error((message) => { 
        alert("Error: " + message); 
       }); 
      this.$scope.uploadPic = function (file) { 
       file.upload = Upload.upload({ 
        url: 'api/upload', 
        data: { name: this.vm.Name, image: this.vm.Image } 
       }); 

       file.upload.then(function (response) { 
        this.$timeout(function() { 
         file.result = response.data; 
        }); 
       }, 
        function (response) { 
         if (response.status > 0) 
          this.$scope.errorMsg = response.status + ': ' + response.data; 
        }); 
      }); 
     } 

     quit() { 
      //quit window funtion 
     } 
    } 
} 

我在CS#-WebApi功能接收文件:

[HttpPost] 
public string Post(string Name, Byte[] Image) 
{ 
    //save the file in database 
} 

我想試圖使角度文件到達WebAPI控制器,並將其視爲Byte [],但我不能。我在做什麼錯了?謝謝大家。

回答

1

你想發佈一個對象

this.$http.post("api/upload", this.vm) 

但你的API期待兩個值

Post(string Name, Byte[] Image) 

試着改變你的API來獲取對象有兩個參數,就像這樣:

public class MyViewModel 
{ 
    public string Name {get;set;} 
    public byte[] File {get;set;} 
} 

[HttpPost] 
public string Post(MyViewModel vm) 
{ 
    //save the file in database 
}