• ASP.NET MVC之文件下载


    http://www.cnblogs.com/zcttxs/archive/2012/05/21/2511947.html

    http://www.cnblogs.com/flashlm/archive/2009/07/25/file_stream_write_method.html

    http://www.cnblogs.com/liang--liang/archive/2012/10/20/2732745.html

    推荐:https://www.cnblogs.com/xiongze520/p/10417472.html

    一、MVC下载

    方式一:

    public FileStreamResult DownFile(string filePath, string fileName)
     {
          string absoluFilePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] +      filePath);
           return File(new FileStream(absoluFilePath, FileMode.Open), "application/octet-stream", Server.UrlEncode(fileName));
     }

    方式二:

    public ActionResult DownFile(string filePath, string fileName)
     {
     filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] + filePath);
     FileStream fs = new FileStream(filePath, FileMode.Open);
     byte[] bytes = new byte[(int)fs.Length];
     fs.Read(bytes, 0, bytes.Length);
     fs.Close();
     Response.Charset = "UTF-8";
     Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
     Response.ContentType = "application/octet-stream";
    
    Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileName));
     Response.BinaryWrite(bytes);
     Response.Flush();
     Response.End();
     return new EmptyResult();
    
    }

    View调用:

    <href="/Document/DownFile?filePath=@item.Value&fileName=@item.Key">下载</a>  

    二、其他下载

    aspx页面:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="上传和下载文件.aspx.cs" Inherits="上传和下载文件" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>无标题页</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:FileUpload ID="homeworkFile" runat="server" />
        <asp:Button ID="btnAdd" runat="server" Text="上传"  OnClick="btnAdd_Click"/></br>
        <asp:Button ID="btndownfile" runat="server" Text="下载方法一:TransmitFile" 
            onclick="btndownfile_Click" /></br>
           <asp:Button ID="btndownfilebyWriteFile" runat="server" 
            Text="下载方法二:WriteFile" onclick="btndownfilebyWriteFile_Click" /></br>
            <asp:Button ID="btndownfilebyWriteFile2" runat="server" 
            Text="下载方法三:WriteFile分块" onclick="btndownfilebyWriteFile2_Click" /><br />
            <asp:Button ID="btndownfilebystream" runat="server" Text="下载方法四:流方式下载" 
            onclick="btndownfilebystream_Click" />
        </form>
    </body>
    </html>
    View Code

    aspx后台代码:

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.IO;
    
    public partial class 上传和下载文件 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            //文件原名
            string fileName = Path.GetFileName(this.homeworkFile.FileName);
            //文件新名字=文件原名+当前时间
            string newFileName = fileName.Substring(0, fileName.IndexOf('.')) + DateTime.Now.ToString("yyyyMMddhhmmss");
            //给文件名加后缀名
            newFileName += fileName.Substring(fileName.IndexOf('.'), fileName.Length - fileName.IndexOf('.'));
            //获得文件存储的路径名
            string Url = ConfigurationManager.AppSettings["ResoursePath"] + ConfigurationManager.AppSettings["RESHomeworkContentPath"] + @"\" + newFileName;
            //验证文件大小
            if (this.IsFileSizeLessMax())
            {  //验证文件的类型
                if (this.isTypeOk(Url))
                {
                    //验证文件存储的路径是否存在
                    string pathStr = ConfigurationManager.AppSettings["ResoursePath"] + ConfigurationManager.AppSettings["RESHomeworkContentPath"];
                    if (!Directory.Exists(pathStr))  //如果不存在路径
                    {
                        Directory.CreateDirectory(pathStr);    //创建路径
                    }
                    if (!Url.Equals(""))    //如果有上传文件
                    {
                        FileUpload fileUpLoad = new FileUpload();
                        //1.存放文件 
                        // fileUpLoad.SaveAs(Url);
                        homeworkFile.PostedFile.SaveAs(Url);
                    }
                }
            }
        }
        /// <summary>
        /// 验证上传文件是否超过规定的最大值
        /// </summary>
        /// <returns></returns>
        private bool IsFileSizeLessMax()
        {
            //返回值
            bool result = false;
            if (this.homeworkFile.HasFile)    //如果上传了文件
            {
                //获取上传文件的允许最大值
                long fileMaxSize = 1024 * 1024;
                try
                {
                    fileMaxSize *= int.Parse(ConfigurationManager.AppSettings["FileUploadMaxSize"].Substring(0, ConfigurationManager.AppSettings["FileUploadMaxSize"].Length - 1));
                }
                catch (Exception ex)
                {
                    //this.WriteException("UserPotal:Homework", ex);
                }
                if (this.homeworkFile.PostedFile.ContentLength > int.Parse(fileMaxSize.ToString()))    //如果文件大小超过规定的最大值
                {
                    //this.ShowMessage("文件超过规定大小。");
                }
                else
                {
                    result = true;
                }
            }
            else    //如果没有上传的文件
            {
                result = true;
            }
            return result;
        }
    
        /// <summary>
        /// 验证文件类型的方法
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool isTypeOk(string fileName)
        {
            //返回结果
            bool endResult = false;
            //验证结果
            int result = 0;
            if (!fileName.Equals(""))    //如果有上传文件
            {
                //允许的文件类型
                string[] fileType = null;
                try
                {
                    fileType = ConfigurationManager.AppSettings["FileType"].Split(',');
                }
                catch (Exception ex)
                {
                    //this.ShowMessage("获取配置文件信息出错");
                    //this.WriteException("AdminProtal:Homework", ex);
                }
                fileName = fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.'));
                for (int i = 0; i < fileType.Length; i++)
                {
                    if (fileType[i].Equals(fileName))    //如果是合法文件类型
                    {
                        result++;
                    }
                }
                if (result > 0)
                {
                    endResult = true;
                }
            }
            else    //如果没有上传文件
            {
                endResult = true;
            }
            return endResult;
        }
        //下载方法一
        protected void btndownfile_Click(object sender, EventArgs e)
        {
            /* 微软为Response对象提供了一个新的方法TransmitFile来解决使用Response.BinaryWrite 下载超过400mb的文件时导致Aspnet_wp.exe进程回收而无法成功下载的问题。 代码如下: */
    
            Response.ContentType = "application/x-zip-compressed";
            Response.AddHeader("Content-Disposition", "attachment;filename=DBintegrate20120521030107.txt");
            string filename = Server.MapPath("BJNetwork/Data/DBintegrate20120521030107.txt");
            Response.TransmitFile(filename);
        }
        //下载方法二
        protected void btndownfilebyWriteFile_Click(object sender, EventArgs e)
        {
            /* using System.IO; */
            string fileName = "DBintegrate20120521030107.txt";//客户端保存的文件名 
            string filePath = Server.MapPath("BJNetwork/Data/DBintegrate20120521030107.txt");//路径 
            FileInfo fileInfo = new FileInfo(filePath);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.WriteFile(fileInfo.FullName);
            Response.Flush();
            Response.End();
    
        }
        //下载方法三
        protected void btndownfilebyWriteFile2_Click(object sender, EventArgs e)
        {
            string fileName = "前台老师和学生界面对比20120521034329.rar";//客户端保存的文件名 
            string filePath = Server.MapPath("BJNetwork/Data/前台老师和学生界面对比20120521034329.rar");//路径 
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
            if (fileInfo.Exists == true)
            {
                const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力 
                byte[] buffer = new byte[ChunkSize];
                Response.Clear();
                System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
                long dataLengthToRead = iStream.Length;//获取下载的文件总大小 
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
                while (dataLengthToRead > 0 && Response.IsClientConnected)
                {
                    int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 Response.OutputStream.Write(buffer, 0, lengthRead); 
                    Response.Flush();
                    dataLengthToRead = dataLengthToRead - lengthRead;
                }
                Response.Close();
            }
    
        }
        //下载方法四
        protected void btndownfilebystream_Click(object sender, EventArgs e)
        {
            string fileName = "前台老师和学生界面对比20120521034329.rar";//客户端保存的文件名 
            string filePath = Server.MapPath("BJNetwork/Data/前台老师和学生界面对比20120521034329.rar");//路径 //以字符流的形式下载文件 
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开 
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    }
    View Code

    web配置文件:

    <appSettings>
         <!--上传文件的路径-->
        <add key="ResoursePath" value="D:\IbeaconShow\BJNetwork"/>
        <add key="RESHomeworkContentPath" value="\Data"/>
        <!--可上传文件的大小-->
        <add key="FileUploadMaxSize" value="20M"/>
        <!--可上传文件类型 -->
        <add key="FileType" value=".zip,.txt,.doc,.rar,.xls,.rtf,.xlsx,.docx,.png"/>
      </appSettings>
    
     <system.web>
         <!--修改asp.net默认上传文件的大小-->
        <httpRuntime executionTimeout="300" maxRequestLength="409600" useFullyQualifiedRedirectUrl="false"/>
    
     </system.web>

     相关文章:https://www.cnblogs.com/carekee/articles/2094675.html

    IIS中上传大小的修改

    1、首先要到进程中把IIS服务关了,即把inetinfo.exe进程关了,不然里面的文件不给你更改的哟~~~
        2、在系统目录中找到:windows/system32/inesrv/metabase.xml”文件,找个文本编辑器打开他,我都用 EditPuls(这家伙不错,带字体色彩的),Ctrl+F 找到AspMaxRequestEntityAllowed="204800"这一项,这就是iis上传文件的默认大小了,默认为204800Byte, 也就是200KB,将它改为你需要的大小就可以了!

    ASP.NET文件下载各种方式比较:对性能的影响、对大文件的支持、对断点续传和多线程下载的支持

    asp.net里提供了多种方式,从服务器端向客户端写文件流,实现客户端下载文件。这种技术在做防下载系统时比较有用处。
    主些技术主要有:WriteFile、TransmitFile和BinaryWrite
    其中WriteFilet和BinaryWrite出现得比较早,对文件流的输出可以启动作用,但由于都是将整个文件读到内存后再往客户端写,因此会占用大量的内存资源,特别是要下载的文件比较大时,影响asp.net应用的稳定运行。
    TransmitFile是为了弥补WriteFile和BinaryWrite的不足才出现的方法,比WriteFile和BinaryWrite更加的稳定强大,对大文件的支持也不错。但其也有不足之处,对断点续传的支持不行,一个大的文件如果一次性没有下载完成的话,就需要从头再来。

    那么一个对性能影响小、支持大文件下载、支持断点续传甚至是多线程下载程序还是需要自己来写的。其实BinaryWrite和WriteFile之所以会影响性能,是因为将整个文件读到内存后再往客户端写,那么我们可以控制他的输出方式,一次只读一块内容到内存,再往客户端写,这些就可以自定义下载的和个细节了。下面提供一个相对不错的下载函数供大家参考。

           /// <summary>
           /// 下载文件,支持大文件、续传、速度限制。支持续传的响应头Accept-Ranges、ETag,请求头Range 。
           /// Accept-Ranges:响应头,向客户端指明,此进程支持可恢复下载.实现后台智能传输服务(BITS),值为:bytes;
           /// ETag:响应头,用于对客户端的初始(200)响应,以及来自客户端的恢复请求,
           /// 必须为每个文件提供一个唯一的ETag值(可由文件名和文件最后被修改的日期组成),这使客户端软件能够验证它们已经下载的字节块是否仍然是最新的。
           /// Range:续传的起始位置,即已经下载到客户端的字节数,值如:bytes=1474560- 。
           /// 另外:UrlEncode编码后会把文件名中的空格转换中+(+转换为%2b),但是浏览器是不能理解加号为空格的,所以在浏览器下载得到的文件,空格就变成了加号;
           /// 解决办法:UrlEncode 之后, 将 "+" 替换成 "%20",因为浏览器将%20转换为空格
           /// </summary>
           /// <param name="httpContext">当前请求的HttpContext</param>
           /// <param name="filePath">下载文件的物理路径,含路径、文件名</param>
           /// <param name="speed">下载速度:每秒允许下载的字节数</param>
           /// <returns>true下载成功,false下载失败</returns>
           public static bool DownloadFile(HttpContext httpContext, string filePath, long speed)
           {
               httpContext.Response.Clear();
               bool ret = true;
               try
               { 
                   #region --验证:HttpMethod,请求的文件是否存在
                   switch (httpContext.Request.HttpMethod.ToUpper())
                   { //目前只支持GET和HEAD方法
                       case "GET":
                       case "HEAD":
                           break;
                       default:
                           httpContext.Response.StatusCode = 501;
                           return false;
                   }
                   if (!File.Exists(filePath))
                   {
                       httpContext.Response.StatusCode = 404;
                       return false;
                   }
                   #endregion
                
                   #region 定义局部变量
                   long startBytes = 0;
                   long stopBytes = 0;
                   int packSize = 1024 * 10; //分块读取,每块10K bytes
                   string fileName = Path.GetFileName(filePath);
                   FileStream myFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                   BinaryReader br = new BinaryReader(myFile);
                   long fileLength = myFile.Length;
                      int sleep = (int)Math.Ceiling(1000.0 * packSize / speed);//毫秒数:读取下一数据块的时间间隔
                   string lastUpdateTiemStr = File.GetLastWriteTimeUtc(filePath).ToString("r");
                   string eTag = HttpUtility.UrlEncode(fileName, Encoding.UTF8) + lastUpdateTiemStr;//便于恢复下载时提取请求头;
                   #endregion
                   
                   #region --验证:文件是否太大,是否是续传,且在上次被请求的日期之后是否被修改过
                   if (myFile.Length > long.MaxValue)
                   {//-------文件太大了-------
                       httpContext.Response.StatusCode = 413;//请求实体太大
                       return false;
                   }
                      if (httpContext.Request.Headers["If-Range"] != null)//对应响应头ETag:文件名+文件最后修改时间
                   {
                       //----------上次被请求的日期之后被修改过--------------
                       if (httpContext.Request.Headers["If-Range"].Replace("\"", "") != eTag)
                       {//文件修改过
                           httpContext.Response.StatusCode = 412;//预处理失败
                           return false;
                       }
                   }
                   #endregion
                   
                   try
                   {
                       #region -------添加重要响应头、解析请求头、相关验证
                       httpContext.Response.Clear();
                          if (httpContext.Request.Headers["Range"] != null)
                       {//------如果是续传请求,则获取续传的起始位置,即已经下载到客户端的字节数------
                           httpContext.Response.StatusCode = 206;//重要:续传必须,表示局部范围响应。初始下载时默认为200
                           string[] range = httpContext.Request.Headers["Range"].Split(new char[] { '=', '-' });//"bytes=1474560-"
                           startBytes = Convert.ToInt64(range[1]);//已经下载的字节数,即本次下载的开始位置  
                           if (startBytes < 0 || startBytes >= fileLength)
                           {//无效的起始位置
                               return false;
                           }
                           if (range.Length == 3)
                           {
                               stopBytes = Convert.ToInt64(range[2]);//结束下载的字节数,即本次下载的结束位置  
                               if (startBytes < 0 || startBytes >= fileLength)
                               {
                                   return false;
                               }
                           }
                       }
                       httpContext.Response.Buffer = false;
                       httpContext.Response.AddHeader("Content-MD5", FileHash.MD5File(filePath));//用于验证文件
                       httpContext.Response.AddHeader("Accept-Ranges", "bytes");//重要:续传必须
                       httpContext.Response.AppendHeader("ETag", "\"" + eTag + "\"");//重要:续传必须
                       httpContext.Response.AppendHeader("Last-Modified", lastUpdateTiemStr);//把最后修改日期写入响应                
                       httpContext.Response.ContentType = "application/octet-stream";//MIME类型:匹配任意文件类型
                       httpContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).Replace("+", "%20"));
                       httpContext.Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                       httpContext.Response.AddHeader("Connection", "Keep-Alive");
                       httpContext.Response.ContentEncoding = Encoding.UTF8;
                       if (startBytes > 0)
                       {//------如果是续传请求,告诉客户端本次的开始字节数,总长度,以便客户端将续传数据追加到startBytes位置后----------
                           httpContext.Response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                       }
                       #endregion
    
                       #region -------向客户端发送数据块-------------------
                       br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                       int maxCount = (int)Math.Ceiling((fileLength - startBytes + 0.0) / packSize);//分块下载,剩余部分可分成的块数
                       for (int i = 0; i < maxCount && httpContext.Response.IsClientConnected; i++)
                       {//客户端中断连接,则暂停
                           httpContext.Response.BinaryWrite(br.ReadBytes(packSize));
                           httpContext.Response.Flush();
                           if (sleep > 1) Thread.Sleep(sleep);
                       }
                       #endregion
                   }
                   catch
                   {
                       ret = false;
                   }
                   finally
                   {
                       br.Close();
                       myFile.Close();
                   }
               }
               catch
               {
                   ret = false;
               }
               return ret;
           }
  • 相关阅读:
    Linux Shell 编程
    Linux下压缩与解压
    rsync实现文件备份同步
    linux中ulimit作用
    3dmax卡通渲染插件pencil+渲染线框
    世嘉开发部部长:这3点能提升游戏留存率
    消息中间件 分布式
    高并发高性能
    你的系统如何支撑高并发
    分布式系统的阿喀琉斯之踵:数据一致性
  • 原文地址:https://www.cnblogs.com/xcsn/p/3099548.html
Copyright © 2020-2023  润新知