开发框架

前端

angularJS1.6

下载和保存文件FileSaver:https://github.com/eligrey/FileSaver.js/

后端

.net WebAPI

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方法

/// <summary>
/// Uploads this instance.
/// </summary>
/// <returns></returns>
[Route("Upload")]
[HttpPost]
public IHttpActionResult Upload() {
if (HttpContext.Current.Request.Files.Count == ) {
return this.Ok(new OperationResultDto() { Result = false, ResultMsg = Message.Error.NoFile });
} var file = HttpContext.Current.Request.Files[];
var mappedPath = HostingEnvironment.MapPath("~/Upload");
var fileFullPath = Path.Combine(mappedPath, Guid.NewGuid().ToString().ToUpper() + Path.GetFileName(file.FileName)); var saveFileResult = this.SaveFile(file, mappedPath, fileFullPath);
if (!saveFileResult.Result) {
return this.Ok(saveFileResult);
} OperationResultDto ret = new OperationResultDto();
string errorMsg = string.Empty;
Dictionary < System.Guid, string > error = new Dictionary < Guid, string > (); try {
// 读取Excel文件,自己实现
// var getImportDataResult = this.GetImportFileData(mappedPath, fileFullPath);
// if (!getImportDataResult.Result) {
// return this.Ok(getImportDataResult);
// } // 业务处理 } catch (Exception ex) {
errorMsg = ex.Message.ToString();
error.Add(System.Guid.NewGuid(), ex.StackTrace.ToString());
} finally {
File.Delete(fileFullPath);
} if (!string.IsNullOrEmpty(errorMsg)) {
ret.ResultMsg = errorMsg;
ret.Errors = error;
} return this.Ok(ret);
} /// <summary>
/// Saves the file.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="mappedPath">The mapped path.</param>
/// <param name="fileFullPath">The file full path.</param>
/// <returns></returns>
private OperationResultDto SaveFile(HttpPostedFile file, string mappedPath, string fileFullPath) {
string errorMsg = string.Empty;
Dictionary < System.Guid, string > error = new Dictionary < Guid, string > ();
try {
if (Directory.Exists(mappedPath) == false) {
Directory.CreateDirectory(mappedPath);
}
file.SaveAs(fileFullPath);
} catch (Exception ex) {
errorMsg = Message.Error.SaveFileError;
error.Add(System.Guid.NewGuid(), ex.StackTrace.ToString());
}
return new OperationResultDto() { ResultMsg = errorMsg, Result = string.IsNullOrEmpty(errorMsg), Errors = error };
}

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代码

Js Controller代码

$scope.down = function() {
testService. download ();
};

Js webservice方法

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文件上传和下载的更多相关文章

  1. java web学习总结(二十四) -------------------Servlet文件上传和下载的实现

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...

  2. (转载)JavaWeb学习总结(五十)——文件上传和下载

    源地址:http://www.cnblogs.com/xdp-gacl/p/4200090.html 在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传 ...

  3. JavaWeb学习总结,文件上传和下载

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...

  4. java文件上传和下载

    简介 文件上传和下载是java web中常见的操作,文件上传主要是将文件通过IO流传放到服务器的某一个特定的文件夹下,而文件下载则是与文件上传相反,将文件从服务器的特定的文件夹下的文件通过IO流下载到 ...

  5. 使用jsp/servlet简单实现文件上传与下载

    使用JSP/Servlet简单实现文件上传与下载    通过学习黑马jsp教学视频,我学会了使用jsp与servlet简单地实现web的文件的上传与下载,首先感谢黑马.好了,下面来简单了解如何通过使用 ...

  6. JavaWeb学习总结(五十)——文件上传和下载

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...

  7. 文件上传和下载(可批量上传)——Spring(三)

    在文件上传和下载(可批量上传)——Spring(二)的基础上,发现了文件下载时,只有在Chrome浏览器下文件名正常显示,还有发布到服务器后,不能上传到指定的文件夹目录,如上传20160310.txt ...

  8. 文件上传和下载(可批量上传)——Spring(二)

    针对SpringMVC的文件上传和下载.下载用之前“文件上传和下载——基础(一)”的依然可以,但是上传功能要修改,这是因为springMVC 都为我们封装好成自己的文件对象了,转换的过程就在我们所配置 ...

  9. Struts2 之 实现文件上传和下载

    Struts2  之 实现文件上传和下载 必须要引入的jar commons-fileupload-1.3.1.jar commons-io-2.2.jar 01.文件上传需要分别在struts.xm ...

随机推荐

  1. org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

    异常信息 org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable represen ...

  2. cron任务解释

    cron本来是在linux下的一个定时任务执行工具,现在很多语言都支持cron,本文参考https://en.wikipedia.org/wiki/Cron,解释一下cron配置. 概述 cron配置 ...

  3. 《程序设计语言——实践之路》【PDF】下载

    程序设计语言--实践之路>[PDF]下载链接: https://u253469.pipipan.com/fs/253469-230382240 内容简介 本书在美国大学已有使用了十余年,目前被欧 ...

  4. 43.Linux调试测试输入思路

    当产品要发布之前,都会进行反复的测试输入,比如:测试按键,遥控,触摸等等. 当出现bug时,就还需要不停地找规律,修改程序,直到修复成功,会显的非常麻烦 答: 可以通过之前在35.Linux-分析并制 ...

  5. 为了CET-4!(二)

    directions: For this part,you are allowed 30 minutes to write an eassay.Suppose there are two option ...

  6. scala写算法-快排

    快排算法很经典,今天用scala的函数式思维来整理一下并实现: def qsort(list: List[Int]):List[Int]=list match { case Nil=>Nil c ...

  7. 【简单理解】gulp和webpack的区别

    Gulp和Webpack的基本区别: gulp可以进行js,html,css,img的压缩打包,是自动化构建工具,可以将多个js文件或是css压缩成一个文件,并且可以压缩为一行,以此来减少文件体积,加 ...

  8. flask入门篇

    flask,Flask是一个使用 Python 编写的轻量级 Web 应用框架.其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2 . Flask简单易学,属于轻量级的,学起来 ...

  9. Elasticsearch5.4常见问题总结

    最近项目中用到了Elasticsearch5.4(ES)是比较新的一个版本,使用的过程中出现了很多的问题,很是头疼,但是问题最终还是解决掉了. 问题一:ESClient获取慢,并且不能获取Client ...

  10. 初识BASH SHELL

    什么是Shell shell翻译成中文就是"壳"的意思.简单来说就是shell是计算机用户与操作系统内核进行"沟通"的一种工具.Windows系统中有power ...