码迷,mamicode.com
首页 > Web开发 > 详细

AngularJs附件上传下载

时间:2016-08-12 19:41:10      阅读:375      评论:0      收藏:0      [点我收藏+]

标签:

首先: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         }

4、后台下载代码

 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         }

 

注:仅个人理解及笔记,有误的地方请各位大神指正!

AngularJs附件上传下载

标签:

原文地址:http://www.cnblogs.com/zfdcp-028/p/5766091.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!