博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
文件下载的几种方法
阅读量:5104 次
发布时间:2019-06-13

本文共 6540 字,大约阅读时间需要 21 分钟。

先把有问题的代码贴出来吧,using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.IO;namespace infoPlatClient.NetDisk{    public partial class downLoad : Com.DRPENG.Common.WebStruct.BaseForm    {        ///         /// 取得要下载文件的路径        ///         private string fileRpath        {            get            {                return Request["fileRpath"] == null ? "" : Request["fileRpath"];            }        }        ///         /// 取得要下载文件的名称        ///                protected void Page_Load(object sender, EventArgs e)        {                if (!IsPostBack)                this.DownloadFile();        }        public void DownloadFile()        {                Response.ClearHeaders();                Response.Clear();                Response.Expires = 0;                Response.Buffer =true;                Response.AddHeader("Accept-Language", "zh-tw");                string name = System.IO.Path.GetFileName(fileRpath);                System.IO.FileStream files = new FileStream(fileRpath, FileMode.Open, FileAccess.Read, FileShare.Read);                byte[] byteFile=null;                if (files.Length == 0)                {                    byteFile=new byte[1];                }                else                {                    byteFile = new byte[files.Length];                }                files.Read(byteFile, 0, (int)byteFile.Length);                files.Close();                             Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));                Response.ContentType = "application/octet-stream;charset=gbk";                Response.BinaryWrite(byteFile);                Response.End();                      }    }} 之前一直用这种下载方式,可是有一次用户上传了一个700Mb的文件时报内存溢出的问题,分析了一下原因,用户的内存只有256M,而下载文件时要创建内存流,导致了内存溢出。解决方案:1>WriteFile分块下载,就是每次下载指定数量的多件;             2>通过超链接的方式;             lblDownLoad.Text = "下载"下面是四种实现文件下载的方式:using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.IO;public partial class _Default : System.Web.UI.Page {    protected void Page_Load(object sender, EventArgs e)    {    }    //TransmitFile实现下载    protected void Button1_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=z.zip");        string filename = Server.MapPath("DownLoad/z.zip");        Response.TransmitFile(filename);    }    //WriteFile实现下载    protected void Button2_Click(object sender, EventArgs e)    {        /*         using System.IO;                  */        string fileName ="asd.txt";//客户端保存的文件名        string filePath=Server.MapPath("DownLoad/aaa.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();    }    //WriteFile分块下载    protected void Button3_Click(object sender, EventArgs e)    {        string fileName = "aaa.txt";//客户端保存的文件名        string filePath = Server.MapPath("DownLoad/aaa.txt");//路径        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 Button4_Click(object sender, EventArgs e)    {        string fileName = "aaa.txt";//客户端保存的文件名        string filePath = Server.MapPath("DownLoad/aaa.txt");//路径        //以字符流的形式下载文件        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();    }}
文件下载的几种方法

 浏览器保存

string name = "对比订单.xls";            using (MemoryStream ms = new MemoryStream())            {                try                {                    wk.Write(ms);                    HttpContext.Response.ContentType = "application/vnd.ms-excel";                    HttpContext.Response.ContentEncoding = Encoding.UTF8;                    HttpContext.Response.Charset = "";                    HttpContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, Encoding.UTF8));                    HttpContext.Response.BinaryWrite(ms.GetBuffer());                    HttpContext.Response.End();                }                catch                {                    HttpContext.Response.Write("false");                }            }
View Code

 

转载于:https://www.cnblogs.com/taidi/p/4093210.html

你可能感兴趣的文章
VC6.0调试技巧(一)(转)
查看>>
类库与框架,强类型与弱类型的闲聊
查看>>
webView添加头视图
查看>>
php match_model的简单使用
查看>>
在NT中直接访问物理内存
查看>>
Intel HEX 文件格式
查看>>
SIP服务器性能测试工具SIPp使用指导(转)
查看>>
php_扑克类
查看>>
回调没用,加上iframe提交表单
查看>>
(安卓)一般安卓开始界面 Loding 跳转 实例 ---亲测!
查看>>
Mysql 索引优化 - 1
查看>>
LeetCode(3) || Median of Two Sorted Arrays
查看>>
大话文本检测经典模型:EAST
查看>>
linux基础命令-chgrp/chown/chomd
查看>>
待整理
查看>>
一次动态sql查询订单数据的设计
查看>>
C# 类(10) 抽象类.
查看>>
Nginx+Keepalived 实现双击热备及负载均衡
查看>>
Vue_(组件通讯)子组件向父组件传值
查看>>
jvm参数
查看>>