AngularJs附件上传下载
首先:angular-file-upload 是一款轻量级的 AngularJS 文件上传工具,为不支持浏览器的 FileAPI polyfill 设计,使用 HTML5 直接进行文件上传。
第一步:引用angularjs的脚本:ng-file-upload-shim.min.js 和 ng-file-upload.min.js
第二步:在angularjs的controller中注入:ngFileUpload
例如:angular.module('liaoyuan.controllers', ['ui.bootstrap', 'ngFileUpload', 'ng.ueditor']);
第三部:写代码
一、上传
1、前台的html代码
1 <form> 2 <!-- <input class="form-control update-input" ngf-select type="file" ng-model="file" name="file" readonly="readonly" /> --> 3 <div class="content"> 4 <label class="update-label">请选择上传的文件位置:</label> 5 6 <input class="filename" type="text" readonly="readonly" /> 7 <a href="javascript:;" class="file-a" name="file"> 8 <input class="file" ngf-select type="file" ng-model="file" name="file" readonly="readonly" />浏览... 9 </a> 10 </div> 11 <button type="button" class="btn btn-primary update-button" style="" ng-click="submit()"> 12 上传 13 </button> 14 <script type="text/javascript"> 15 var file = $('.file'), 16 aim = $('.filename'); 17 file.on('change', function( e ){ 18 var name = e.currentTarget.files[0].name; 19 aim.val( name ); 20 }); 21 </script> 22 </form>
2、angularjs 控制器Controller中的代码
1 app.controller('FileController', function ($scope, $uibModalInstance, Upload) { 2 //取消 3 $scope.cancel = function () { 4 $uibModalInstance.dismiss('cancel'); 5 }; 6 //上传按钮 7 $scope.submit = function () { 8 $scope.upload($scope.file); 9 }; 10 11 $scope.upload = function (file) { 12 $scope.fileInfo = file; 13 Upload.upload({ 14 //服务端接收 15 method: 'POST', 16 url: 'http://localhost:56897/api/serviceLogAttachments', 17 file: file 18 }).progress(function (evt) { 19 //进度条 20 var progressPercentage = parseInt(100.0 * evt.loaded / evt.total); 21 console.log('progess:' + progressPercentage + '%' + evt.config.file.name); 22 }).success(function (newAttachment) { 23 //上传成功 24 $uibModalInstance.close(newAttachment); 25 }).error(function (data, status, headers, config) { 26 //上传失败 27 console.log('error status: ' + status); 28 }); 29 }; 30 31 32 33 });
注意:Upload一定要注入
3、后台上传代码
1 [HttpPost] 2 public IHttpActionResult PostAttachment() 3 { 4 int logId = 1; 5 HttpContext.Current.Response.ContentType = "application/json"; 6 HttpFileCollection files = HttpContext.Current.Request.Files; 7 HttpRequestMessage h = new HttpRequestMessage(); 8 var file = files[0]; 9 string fileExt = Path.GetExtension(file.FileName); 10 11 string attachmentName = file.FileName.Substring(0, file.FileName.LastIndexOf(".")); 12 13 string fileNewName = attachmentName + DateTime.Now.ToString("yyyyMMddHHmmssfff")+ fileExt; 14 15 string strRelativeDir = "/Upload/服务管理/日志详情附件/"; 16 17 string fliePath = HttpContext.Current.Request.MapPath(strRelativeDir); 18 if (!Directory.Exists(fliePath)) 19 { 20 Directory.CreateDirectory(fliePath); 21 } 22 string strSavePath = Path.Combine(fliePath, fileNewName); 23 file.SaveAs(strSavePath); 24 //插入数据库 25 ServiceLogAttachmentService.AddAttachment(attachment); 26 return CreatedAtRoute("DefaultApi", new{id = attachment.AttachmentID}, attachment); 27 }
二、下载
1、前台下载代码
方法一:直接访问后台数据(但此方法在前后台有授权与验证的时候,会不方便)
1 //附件下载 2 $scope.fileDown = function (url, name) { 3 window.location.href = "http://localhost:56888/api/ServiceStateChanges?url=" + url + "&fileName=" + name; 4 }
方法二:在请求数据时在header上加上验证的token
1 //附件下载 2 $scope.fileDown = function (url, name) { 3 var xhr = new XMLHttpRequest(); 4 xhr.responseType = "blob"; 5 6 xhr.open("GET", "http://localhost:56888/api/ServiceStateChanges?url=" + url + "&filename=" + name + "", true); 7 8 xhr.setRequestHeader("Authorization", 'Bearer ' + currUser.token); 9 10 xhr.onreadystatechange = function (e) { 11 if (this.readyState == 4) { 12 var response = this.response; 13 var URL = window.URL || window.webkitURL || window; 14 var link = document.createElement('a'); 15 link.href = URL.createObjectURL(response); 16 link.download = name; 17 var event = document.createEvent('MouseEvents'); 18 event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); 19 link.dispatchEvent(event); 20 } 21 } 22 xhr.send(null); 23 }
2、后台下载代码
1 public HttpResponseMessage GetFile(string url,string fileName) 2 { 3 try 4 { 5 var FilePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/"+ url); 6 System.IO.FileStream stream=null; 7 stream = new FileStream(FilePath, FileMode.Open); 8 HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); 9 response.Content = new StreamContent(stream); 10 response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); 11 response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") 12 { 13 FileName = fileName 14 }; 15 return response; 16 } 17 catch 18 { 19 return new HttpResponseMessage(HttpStatusCode.NoContent); 20 } 21 }
注:仅个人理解及笔记,有误的地方请各位大神指正!