我必须为该网站创建一个测验系统。我必须使用angularjs和webapi在单个页面上上传图像类型问题以及图像类型选项。我想在api中检查哪个图像用于选项,哪个图像用于问题图像,而图像数组名称可见,我可以在数组中显示图像,这是我的代码:
app.directive('uploadFiles', function () {
return {
scope: true, //create a new scope
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var files = event.target.files;
console.info(files);
for (var i = 0; i < files.length; i++) {
scope.$emit("seletedFile", { file: files[i] });
}
});
}
};
});
app.controller('questionairController', function ($scope, $http) {
$scope.files = [];
$scope.$on("seletedFile", function (event, args) {
$scope.fileList = true;
$scope.$apply(function () {
$scope.files.push(args.file);
});
});
$scope.addQuestionair = function () {
var cID = document.getElementById("CustomerID").value;
var pID = document.getElementById("ProjectID").value;
$scope.question.CustomerID = cID;
$scope.question.ProjectID = pID;
console.info($scope.question);
console.info($scope.OptionsList);
var viewObj = {
questionair: $scope.question,
options: $scope.OptionsList
};
console.info(viewObj);
$http({
method: 'POST',
url: 'api/Questions/AddQuestion',
headers: { 'Content-Type': undefined },
uploadEventHandlers: {
progress: function (e) {
if (e.lengthComputable) {
var progressValue = (e.loaded / e.total) * 100;
$scope.ProgressWidth = 0;
$scope.ProgressWidth = { 'width': progressValue + '%' };
}
}
},
transformRequest: function (data) {
console.info("in transform");
var formData = new FormData();
formData.append("model", angular.toJson(data.model));
for (var i = 0; i < data.files.length; i++) {
formData.append(data.files[i].name, data.files[i]);
}
return formData;
},
data: { model: viewObj, files: $scope.files }
}).then(function (response) {
console.info(response);
$scope.SaveMessage = response.data;
GetQuestionair();
$scope.question = null;
}, function (error) {
});
};
这是我的API函数
[HttpPost]
public HttpResponseMessage AddQuestion()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
HttpFileCollection hfc = HttpContext.Current.Request.Files;
var model = HttpContext.Current.Request["model"];
ViewModel viewModel = Newtonsoft.Json.JsonConvert.DeserializeObject<ViewModel>(model);
if (viewModel == null)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
var root = HttpContext.Current.Server.MapPath("~/SiteImages/");
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
HttpPostedFile hpf = hfc[0];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(root + "/" + Path.GetFileName(hpf.FileName));
}
{
db.Tbl_Questionair.Add(viewModel.questionair);
db.SaveChanges();
foreach (var item in viewModel.options)
{
item.CreatedOn = DateTime.Now;
item.QID = viewModel.questionair.ID;
item.CustomerID = viewModel.questionair.CustomerID;
item.ProjectID = viewModel.questionair.ProjectID;
db.Options.Add(item);
db.SaveChanges();
}
return Request.CreateResponse(HttpStatusCode.OK, "Data successfully saved!");
}
}