标签:
由于前段时间一直在找工作,找到工作后又比较忙,又加班又通宵的赶项目,所以博客有段时间没有更新了。
今天稍微空闲一点,碰巧前几天看到有园友问我Nancy中下载文件的问题,然后就趁着休息的时间写下了这篇博客。
1 public class CustomRootPathProvider : IRootPathProvider 2 { 3 public string GetRootPath() 4 { 5 return AppDomain.CurrentDomain.GetData(".appPath").ToString(); 6 } 7 }
1 public class Bootstrapper : DefaultNancyBootstrapper 2 { 3 protected override IRootPathProvider RootPathProvider 4 { 5 get 6 { 7 return new CustomRootPathProvider(); 8 } 9 } 10 }
1 using Nancy; 2 using System.Collections.Generic; 3 using System.IO; 4 5 namespace NancyUpLoadAndDownloadDemo.Modules 6 { 7 public class HomeModule : NancyModule 8 { 9 public HomeModule(IRootPathProvider pathProvider) : base("/") 10 { 11 var uploadDirectory = Path.Combine(pathProvider.GetRootPath(), "Content", "uploads"); 12 13 Get["/"] = _ => 14 { 15 return View["UpLoad"]; 16 }; 17 18 Post["/"] = _ => 19 { 20 21 if (!Directory.Exists(uploadDirectory)) 22 { 23 Directory.CreateDirectory(uploadDirectory); 24 } 25 26 foreach (var file in Request.Files) 27 { 28 var filename = Path.Combine(uploadDirectory, file.Name); 29 using (FileStream fileStream = new FileStream(filename, FileMode.Create)) 30 { 31 file.Value.CopyTo(fileStream); 32 } 33 } 34 return Response.AsRedirect("/show") ; 35 }; 36 37 Get["/down/{name}"] = _ => 38 { 39 string fileName = _.name; 40 var relatePath = @"Content\uploads\"+fileName; 41 return Response.AsFile(relatePath); 42 }; 43 44 Get["/show"] = _ => 45 { 46 var folder = new DirectoryInfo(uploadDirectory); 47 IList<string> files = new List<string>(); 48 foreach (var file in folder.GetFiles()) 49 { 50 files.Add(file.Name); 51 } 52 return View["Show", files]; 53 }; 54 } 55 } 56 }
1 @{ 2 Layout = null; 3 } 4 5 <!DOCTYPE html> 6 7 <html> 8 <head> 9 <meta name="viewport" content="width=device-width" /> 10 <title></title> 11 </head> 12 <body> 13 <ul> 14 @foreach (var item in Model) 15 { 16 <li> 17 <a href="/down/@item"> 18 @item 19 </a> 20 </li> 21 } 22 </ul> 23 </body> 24 </html> 25
1 @{ 2 Layout = null; 3 } 4 5 <!DOCTYPE html> 6 7 <html> 8 <head> 9 <meta name="viewport" content="width=device-width" /> 10 <title>UpLoad</title> 11 </head> 12 <body> 13 <h1>这是上传文件的演示</h1> 14 <hr /> 15 <form action="/" method="post" enctype="multipart/form-data"> 16 17 <div> 18 <label>请选择要上传的文件</label> 19 <input type="file" name="myFile" /> 20 </div> 21 <div> 22 <input type="submit" value="上传" /> 23 </div> 24 25 </form> 26 </body> 27 </html>
标签:
原文地址:http://www.cnblogs.com/catcher1994/p/5294042.html