我使用输入类型文件和其他用户数据上传图像。我的模型由User类组成:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Rollno { get; set; }
public byte[] ProfileImage { get; set; }
public HttpPostedFile image { get; set; }
}
和asp.net mvc中的发布方法:
public ActionResult AddUser(User user)
{
var files = Request.Files;
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
byte[] uploadFile = new byte[file.InputStream.Length];
}
return View();
}
我有一个像这样的输入标签:
<input id="imgInp" type="file" aria-label="Add photos to your post" class="upload" name="file" onchange="angular.element(this).scope().LoadFileData(this.files)" multiple="" accept="image/*">
和这样的angularJS控制器:
angular.module('app', ['AngularDemo.BeerController']).
controller('formController',['$scope','$http', function ($scope,$http) {
alert('in controller');
var formData = new FormData();
$scope.LoadFileData = function (files) {
for (var file in files) {
formData.append("file", files[file]);
}
};
$scope.submit = function () {
alert('in submit');
$http.post("/Home/AddUser", formData, {
withCredentials: true,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
}).success(function (response) {
});
}
}]);
我的图片文件在AddUser
方法中发回,但如何发送模型数据?我在表单中添加了ng-model="Name"
等。由于我的$scope.Name
将表单数据作为传递数据,如何向$http.post
等发送该图像数据?
答案 0 :(得分:0)
如果将User作为JSON字符串传递,则可以使此工作正常。但是,这不会绑定[HttpPost]
public ActionResult AddUser(string user, HttpPostedFileBase[] files)
{
// parse user into User
}
类的图像属性。
<input id="imgInp" type="file" aria-label="Add photos to your post" class="upload" name="file"
onchange="angular.element(this).scope().LoadFileData(this.files)" multiple="" accept="image/*">
<input name="Id" type="text" ng-model="user.Id" />
<input name="Name" type="text" ng-model="user.Name" />
表单字段
.controller('formController',['$scope','$http', function ($scope, $http) {
$scope.user = {
Id: 0,
Name: ""
};
$scope.files = [];
$scope.LoadFileData = function(files) {
$scope.files = files;
};
$scope.submit = function() {
$http({
url: "/Home/AddUser",
method: "POST",
headers: { "Content-Type": undefined },
transformRequest: function(data) {
var formData = new FormData();
formData.append("user", angular.toJson(data.user));
for (var i = 0; i < data.files.length; i++) {
formData.append("files[" + i + "]", data.files[i]);
}
},
data: { user: $scope.user, files: $scope.files }
})
.success(function(response) { });
};
});
和角度控制器
User
如果您不想将JSON解析为public ActionResult AddUser(string userName, int userId, HttpPostedFileBase[] files) { ... }
,那么您必须编写自定义活页夹。如果没有很多用户字段,您可以将它们作为离散参数传递。
{{1}}