我从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 [],但我不能。我究竟做错了什么?谢谢大家。
答案 0 :(得分:2)
您尝试发布对象
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
}