前端:
<form class="form-horizontal tasi-form" method="post">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" ng-click="cancel()">×</button>
<h4 class="modal-title">{{formTitle.title}}</h4>
</div>
<div class="modal-body">
<input type="file" id="file" name="file" class="btn btn-warning pull-left" ng-src={{files[0].name}} onchange='angular.element(this).scope().fileChanged(this)' />
</div>
<div class="modal-footer" style="display: block">
<button class="btn btn-primary" ng-click="updateTplConfirm()">确定</button>
<button class="btn btn-disabled" ng-click="cancel()">关闭</button>
</div>
</div>
</form>
控制器:
$scope.fileChanged = function (ele) {
$scope.files = ele.files;
$scope.$apply(); //传播Model的变化。
}
$scope.updateTplConfirm = function () {
//angular不支持file的ng-model双向绑定
var fd = new FormData();
var file = document.querySelector('input[type=file]').files[0];
var filename = $scope.files[0].name;
if (filename.length > 1 && filename)
{
var ldot = filename.lastIndexOf(".");
var type = filename.substring(ldot + 1);
if(type != "pdf") {
toastr.warning("只能上传PDF文件!");
}else{
TplConfigService.updateTpl({},file,function (data) {
if (data != null && data.state == 1) {
toastr.success("模板更新成功!");
$scope.cancel();
} else {
toastr.warning("模板更新失败!");
}
});
}
}
};
服务类:
//上传文件
uploadFile: function (url,par) {
var deferred = $q.defer();
Upload.upload({
//服务端接收
url: serviceBase + url,
//上传的同时带的参数
data: par,
file: file
}).progress(function (evt) {
//进度条
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
$rootScope.progressPercentage = progressPercentage;
console.log('progess:' + progressPercentage + '%');
}).success(function (data,status,headers,config) {
//上传成功
deferred.resolve(data);
}).error(function (data,config) {
//上传失败
console.log('error status: ' + status + data);
});
return deferred.promise;
},
注入:
commonService.service('CommonService',['$rootScope', '$q','$timeout','$http', '$state','$uibModal','Settings','$window','$localStorageUsage','$loading','toastr','Upload',function ($rootScope,$q,$timeout,$http,$state,$uibModal,Settings,$window,$localStorageUsage,$loading,toastr,Upload) {
注意:'$q','$http' 是Upload的依赖模块。
C#后端:
/// <summary>
/// 更新模板
/// </summary>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public MessageRs UpdateTpl() //注意不要加入参
{
HttpFileCollection files = HttpContext.Current.Request.Files;
return null;
}
界面:
原文链接:https://www.f2er.com/angularjs/145803.html