zoukankan      html  css  js  c++  java
  • mvc开发模式下进行文件的下载

    在这里主要是讲一下mvc的文件下载操作,现在本人是要做一个mvc的小项目,用的是mvc3.0,所以这里以mvc3.0讲解下吧,

    其实code也非常简单,如果对下载这块儿还存在疑惑的code Man...  看完本篇小demo,定会捂嘴偷笑...  咱开始吧

    第一步:在controller里的action这样定义

     public ActionResult DownLoad()
            {
                return new DownloadResult { VirtualPath = "~/content/Sth/testDemo.rar", FileDownloadName = "DownFileName.rar" };
            }

    这里的 Virtualpath 表示你要设置下载的文件是哪个? 我这里是获取content文件夹下面的sth文件夹下面的testDemo.rar文件。然后设置FileDownloadName 为你要下载时保存的文件名字是什么,我这里设置的为下载时默认保存为DownFileName.rar

    第二步:创建DownloadResult类,该类主要是设置下载时的一些必须的参数,code 如下:

     1  public class DownloadResult : ActionResult
     2     {
     3 
     4         public DownloadResult()
     5         {
     6         }
     7 
     8         public DownloadResult(string virtualPath)
     9         {
    10             this.VirtualPath = virtualPath;
    11         }
    12 
    13         public string VirtualPath
    14         {
    15             get;
    16             set;
    17         }
    18 
    19         public string FileDownloadName
    20         {
    21             get;
    22             set;
    23         }
    24         public override void ExecuteResult(ControllerContext context)
    25         {
    26             if (!String.IsNullOrEmpty(FileDownloadName))
    27             {
    28                 context.HttpContext.Response.AddHeader("content-disposition",
    29                   "attachment; filename=" + this.FileDownloadName);
    30             }
    31 
    32             string filePath = context.HttpContext.Server.MapPath(this.VirtualPath);
    33             context.HttpContext.Response.TransmitFile(filePath);
    34         }
    35     }

    该类主要是对 VirtualPathFileDownloadName进行初始一下,很重要的一点是AddHeader("content-disposition","attachment; filename="+ this.FileDownloadName);

     this.FileDownloadName 是在action里new DownloadResult类时,传进来的参数, 下面的Server.MapPath是保存下载文件在什么地方,根据用户选择而定。

    第三步:主要是在view里进行操作了,这里可以使用测试单元进行测试(我这里就直接在view里操作吧) code 如下:

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4     <title>下载示例</title>
     5 </head>
     6 <body>
     7     <div>
     8         <a href=@Url.Content("/test/DownLoad")>下载</a>
     9     </div>
    10 </body>
    11 </html>

    这里的 /test/downLoad 就是指向我第一步时创建的action,

    相信大家 看到这里,对mvc模式下的下载应该掌握了吧。嘻嘻

       若能帮助到你,万分荣幸

      

  • 相关阅读:
    PAT 1010. 一元多项式求导 (25)
    PAT 1009. 说反话 (20) JAVA
    PAT 1009. 说反话 (20)
    PAT 1007. 素数对猜想 (20)
    POJ 2752 Seek the Name, Seek the Fame KMP
    POJ 2406 Power Strings KMP
    ZOJ3811 Untrusted Patrol
    Codeforces Round #265 (Div. 2) 题解
    Topcoder SRM632 DIV2 解题报告
    Topcoder SRM631 DIV2 解题报告
  • 原文地址:https://www.cnblogs.com/oldcell/p/3083562.html
Copyright © 2011-2022 走看看