webAPI+angularJS文件上传和下载
2021-04-26 06:25
标签:ati cto request ret null 分享 dialog route upper angularJS1.6 下载和保存文件FileSaver:https://github.com/eligrey/FileSaver.js/ .net WebAPI Js Controller代码 Js webservice方法 webAPI+angularJS文件上传和下载 标签:ati cto request ret null 分享 dialog route upper 原文地址:http://www.cnblogs.com/tianxue/p/7898964.html开发框架
前端
后端
1 导入Excel文件关键代码
1.1 导入Excel弹出框
1.2 模态框html代码
div class="modal fade" id="importExcelPop" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
div class="modal-dialog" style="width:610px;height:100px;" role="document">
div class="modal-content">
div class="modal-header">
div class="modal-title">导入Excel文件div>
div>
div class="modal-body">
form class="form-horizontal" id="importExcelForm">
div class="form-group">
label for="import" class="col-sm-2 control-label">选择文件:label>
div class="col-sm-5">
div class="form-control" type="text" name="fileName" readonly placeholder="" ng-required="isAdd" title="{{file ? file.name : ‘‘}}">
{{file ? file.name : ‘‘ | limitString :20}}
div>
div>
div class="col-sm-5">
button type="button" type="file" ngf-select ng-model="file" accept=".xls,.xlsx" class="btn btn-not-important browse inline-div">{{‘Browse‘ | translate }}button>
div>
div>
form>
div>
div class="modal-footer" style="padding-left:113px;">
button type="button" class="btn btn-primary" ng-disabled="!file" ng-click=”upload()">导入button>
button type="button" class="btn btn-third" data-dismiss="modal">取消button>
div>
div>
div>
div>
1.3 导入js代码
// 上传文件地址
var uploadUrl = apiInterceptor.webApiHostUrl + ‘/test/Upload‘;
// angularjs上传方法
$scope.upload = function() {if ($scope.file) {
// 选中文件
importData();
}
};
// 导入数据
var importData = function() {
if (!$scope.file || !$scope.file.name) {
SweetAlert.info(‘请选择文件‘);
return;
}
// $q需要注入
var deferred = $q.defer();
var tempFileName = PWC.newGuid() + ‘.dat‘;
var token = $(‘input[name="__RequestVerificationToken"]‘).val();
Upload.upload({
url: uploadUrl,
data: {
cancel: false,
filename: $scope.file.name,
},
file: $scope.file,
resumeChunkSize: resumable ? $scope.chunkSize : null,
headers: {
‘Access-Control-Allow-Origin‘: ‘*‘,
Authorization: apiInterceptor.tokenType + ‘ ‘ + apiInterceptor.apiToken,
__RequestVerificationToken: token,
withCredentials: true
},
__RequestVerificationToken: token,
withCredentials: true
}).then(function(resp) {
var ret = resp.data;
deferred.resolve();
}, function(resp) {
deferred.resolve();
console.log(‘Error status: ‘ + resp.statusText);
}, function(evt) {
deferred.resolve();
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
$log.debug(‘progress: ‘ + progressPercentage + ‘% ‘ + evt.config.data.file.name);
});
};
1.4 webAPI的TestController方法
///
2 下载Excel关键代码
2.1 UI
2.2 html代码
button type="button" class="btn" ng-click="down ()"> i class="fa fa-download" aria-hidden="true">i>下载模板button>
2.3 js代码
$scope.down = function() {
testService. download ();
};
download: function() {
var thisConfig = apiConfig.create();
thisConfig.responseType = "arraybuffer";
return $http.post(‘/test/download‘, {}, thisConfig).then(function(response) {
var data = new Blob([response.data], { type: response.headers(‘Content-Type‘) });
// var filename1 = response.headers(‘Content-Disposition‘).split(‘;‘)[1].trim().substr(‘filename=‘.length);
var filename = ‘Excel.xlsx‘;
// FileSaver 是一个插件
FileSaver.saveAs(data, filename);
});
}
2.4 webAPI方法
[HttpPost]
[Route("download")]
public HttpResponseMessage Download (object o) {
var filePath = HostingEnvironment.MapPath("~/downLoad/Excel.xlsx");
string customFileName = Constant.FileName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"; //客户端保存的文件名
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
fileStream.CopyTo(ms);
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new ByteArrayContent(ms.ToArray());
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = customFileName;
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 这句话要告诉浏览器要下载文件
return response;
}
文章标题:webAPI+angularJS文件上传和下载
文章链接:http://soscw.com/index.php/essay/79688.html