Response.AddHeader实现下载,解决乱码问题

本文介绍了在ASP.NET中使用Response.AddHeader实现下载,同时解决了文件名乱码问题。详细讲解了分块下载、HttpResponse.TransmitFile方法、WriteFile方法以及流方式下载,并探讨了HTTP响应头和实体头的相关设置,确保下载过程的正确性和效率。
摘要由CSDN通过智能技术生成

最近处理下载,顺便整理一下代码以便以后使用,直接上代码:

1、分块下载

            try
            {
                var templatePath = "/Download/test.xls";

                string filename = Server.MapPath(templatePath);

                System.IO.FileInfo fileInfo = new System.IO.FileInfo(filename);
                if (fileInfo.Exists == true)
                {
                    const long chunkSize = 204800;// 每次读取200K,缓解服务器的压力
                    byte[] buffer = new byte[chunkSize];

                    Response.Clear();
                    System.IO.FileStream iStream = System.IO.File.OpenRead(filename);
                    long dataLengthToRead = iStream.Length;//获取下载的文件总大小
                    Response.ContentType = "application/vnd.ms-excel";
                    Response.AddHeader("Content-Disposition", "attachment;filename="+ HttpUtility.UrlEncode("XXXXXX模板.xls"));
                    Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                    Response.AddHeader("Content-Transfer-Encoding", "binary");
                    Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
                    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();
                }
            }
            catch (Exception)
            {
                Response.Write("服务器异常,请稍后再试!");
            }

注:

1、分块读取到内存然后下载,不怕内存溢出。

2、HttpUtility.UrlEncode对文件名进行编码,可防止下载时乱码


以下几个来自网络,传送门

2、HttpResponse.TransmitFile 方法

	Response.ContentType = "application/x-zip-compressed";
        Response.AddHeader("Content-Disposition", "attachment;filename=z.zip");
        string filename = Server.MapPath("DownLoad/z.zip");
        Response.TransmitFile(filename);

注:msdn解释为:将指定的文件直接写入 HTTP 响应输出流,而不在内存中缓冲该文件。明显不适合大文件

3、WriteFile方法

        string fileName ="test.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();

4、流方式下载

        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();


HTTP响应头和实体头

以下内容来自维基百科

响应字段

Field name Description Example Status
Access-Control-Allow-Origin 指定哪些网站可参与到 跨来源资源共享 过程中  Access-Control-Allow-Origin: * Provisional
Accept-Patch[23] Specifies which patch document formats this server supports Accept-Patch: text/example;charset=utf-8 Permanent
Accept-Ranges 这个服务器支持哪些种类的部分内容范围  Accept-Ranges: bytes Permanent
Age 这个对象在 代理缓存 中存在的时间,以秒为单位  Age: 12 Permanent
Allow 对于特定资源有效的动作。针对405不允许该方法( 405 Method not allowed )而使用  Allow: GET, HEAD Permanent
Cache-Control 向从服务器直到客户端在内的所有缓存机制告知,它们是否可以缓存这个对象。其单位为秒  Cache-Control: max-age=3600 Permanent
Connection 针对该连接所预期的选项

[3]

Connection: close Permanent
Content-Disposition[24] An opportunity to raise a "File Download" dialogue box for a known MIME type with binary format or suggest a filename for dynamic content. Quotes are necessary with special characters. Content-Disposition: attachment; filename="fname.ext" Permanent
Content-Encoding 在数据上使用的编码类型。参考 超文本传输协议压缩 。  Content-Encoding: gzip Permanent
Content-Language 内容所使用的语言

[25]

Content-Language: da Permanent
Content-Length 回应消息体的长度,以 字节 (8位为一字节)为单位  Content-Length: 348 Permanent
Content-Location 所返回的数据的一个候选位置  Content-Location: /index.htm Permanent
Content-MD5 回应内容的二进制 MD5 散列,以 Base64 方式编码 
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值