本文介绍了使用angularjs上载多个文件,并为每个文件添加自定义数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我上了这样的课
public class UnitDocuments
{
public int UnitId { get; set; }
public int DocType { get; set; }
public HttpPostedFileBase UpFile { get; set; }
}
我尝试构建自己的函数以使用angular js将数据从html页面发送到mvc控制器
I try to build my own function to send data from html page to mvc controller using angular js
角度js模型如下
{"UnitId":0,"DocType":1,"UpFile":{}}]
并使用angularjs指令,我可以用上传的数据填充UpFile,例如帖子此处且模型已更改
and using angularjs directive i can fill the UpFile with uploaded data like the post Hereand the model changed
[{"UnitId":0,"DocType":1,"UpFile":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADQAAAAlCAYAAAAN8sr"},[{"UnitId":0,"DocType":5,"UpFile":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADQAAAAlCAYAAAAN8sr"}]]
将其发送到MVC Controller时,总是获得UpFile的空值
when send this to MVC Controller always get null value for UpFile
public ActionResult Create(List<UnitDocuments> unitDocuments)
{
}
有什么办法可以做这样的事情吗?我希望unitDocuments列表中的每个项目都有一个文件及其相关数据
is there any way to do something like this ? i expect for each item in unitDocuments list there is a file with its related data
推荐答案
布局页面
<html ng-app="myFormApp">
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
<script src="~/Scripts/Demo/angular.js"></script>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
<style>
.layout-header {
background-color: #0090c3;
height: 75px;
margin-bottom: 1%;
}
</style>
</head>
<body>
<div class="layout-header">
</div>
<div>
@RenderBody()
</div>
</body>
</html>
app.directive('fileUpload', function () {
return {
scope: true, //create a new scope
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var files = event.target.files;
//iterate files since 'multiple' may be specified on the element
for (var i = 0; i < files.length; i++) {
//emit event upward
scope.$emit("fileSelected", { file: files[i] });
}
});
}
};
});
INDEX.CSHTML
INDEX.CSHTML
<div ng-controller="CTRL_Demo">
<input type="hidden" ng-model="CTRL_Demo.Id"/>
<input type="text" ng-model="CTRL_Demo.FirstName" />
<input type="text" ng-model="CTRL_Demo.LastName"/>
<input type="file" name="file" file-upload />
<button ng-click="SaveEmployee()" class="btn btn-primary">SAVE</button>
</div>
角度控制器代码
var app = angular.module('myFormApp', []);
app.controller('CTRL_Demo', function ($scope, $http) {
$scope.CTRL_Demo = {};
$scope.CTRL_Demo.Id = 101;
$scope.files = [];
$scope.$on("fileSelected", function (event, args) {
$scope.$apply(function () {
$scope.files.push(args.file);
});
});
$scope.GetUserList = function () {
$http.get("/User/GetEmployee")
.then(function (response) {
console.log(response.data);
});
}
$scope.GetUserList();
$scope.SaveEmployee = function () {
var formData = new FormData();
formData.append("Id", $scope.CTRL_Demo.Id);
formData.append("FirstName", $scope.CTRL_Demo.FirstName);
formData.append("LastName", $scope.CTRL_Demo.LastName);
for (var i = 0; i < $scope.files.length; i++) {
formData.append("file" + i, $scope.files[i]);
}
$http({
method: 'POST',
url: "/User/SaveEmployee",
headers: { 'Content-Type': undefined },
processData: false,
contentType: false,
data: formData,
transformRequest: angular.identity,
}).success(function (data, status, headers, config) {
alert("success!");
}).error(function (data, status, headers, config) {
alert("failed!");
});
}
$scope.uploadFile = function (files) {
var fd = new FormData();
fd.append("file", files[0]);
$http.post('@Url', fd, {
withCredentials: true,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
}).success(function () {
}).error(function () {
});
};
});
MVC控制器代码
MVC CONTROLLER CODE
[HttpPost]
public JsonResult SaveEmployee(UserViewModel model)
{
string _fileName = "";
if (Request.Files.Count > 0)
{
var _empid = int.Parse(Request.Form["Id"]);
var _file = Request.Files[0];
var _fName = Request.Files["file0"].FileName;
var _dotIndex = _fName.LastIndexOf('.');
var _ext = _fName.Substring(_dotIndex);
var _configpath = RequestHelpers.GetConfigurationValue("ImageUpload");
_fileName = _empid + "_IDPROOF" + _ext;
var _dirPath = Server.MapPath(_configpath);
var _filePath = Server.MapPath(_configpath) + _fileName;
if (System.IO.Directory.Exists(_dirPath))
{
if (System.IO.File.Exists(_filePath))
{
System.IO.File.Delete(_filePath);
}
_file.SaveAs(_filePath);
}
else
{
System.IO.Directory.CreateDirectory(_dirPath);
_file.SaveAs(_filePath);
}
}
return Json(_IUser_Repository.GetUser(),JsonRequestBehavior.AllowGet);
}
这篇关于使用angularjs上载多个文件,并为每个文件添加自定义数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!