.Net服务器下发文件

字符串是数据的一种,文件也是,他们的本质都是二进制。在网络上传输时,数据都是流的形式(二进制),所以服务器能返回字符串,也能返回其他数据类型,主要设置相关HTTP响应头来完成,话不多说,直接上代码(.Net)。

    /// <summary>
    /// DownloadFile 的摘要说明
    /// 参考:http://www.cnblogs.com/qiuweiguo/archive/2011/06/30/2094445.html
    /// </summary>
    public class DownloadFile : IHttpHandler
    {
        // 1.Url, 2.Extension
        #region 传参
        //下载地址
        private string DownloadUrl = string.Empty;
        //扩展名
        private string Extension = string.Empty;
        //指定文件名,若不指定为默认
        private string fileName = "";
        #endregion
        public void ProcessRequest(HttpContext context)
        {
            DownloadUrl = context.Request["downloadUrl"];
            Extension = context.Request["extension"];
            fileName =FunLayer.Transform.Str(context.Request["fileName"],"");
            WebClient wc = new WebClient();
            byte[] zipBytes = wc.DownloadData(DownloadUrl);
            MemoryStream zipStream = new MemoryStream(zipBytes);
            byte[] fileBytes = default(byte[]);
            fileBytes = Method.ZipUtility.UnZipFile(zipStream);
            ///当代码里面使用Content-Disposition来确保浏览器弹出下载对话框的时候。
            ///response.addHeader("Content-Disposition","attachment");一定要确保没有做过关于禁止浏览器缓存的操作。
            ///不然会发现下载功能在opera和firefox里面好好的没问题,在IE下面就是不行,就是找不到文件。
            context.Response.Expires = 0;
            context.Response.AddHeader("Pragma", "No-cache");
            context.Response.AddHeader("Cache-Control", "No-cache");
            ///以编码方式解决IE下中文文件名乱码
            if (!string.IsNullOrEmpty(fileName))
            {
                fileName=HttpUtility.UrlEncode(System.Text.UTF8Encoding.UTF8.GetBytes(fileName));
            }

            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + (string.IsNullOrEmpty(fileName) ? "1." : fileName) + Extension + "");//设置文件名
            context.Response.AddHeader("Content-Length", fileBytes.Length.ToString());//设置下载文件大小
            //HTTP ContentType 对照表 http://tool.oschina.net/commons
            context.Response.ContentType = "application/octet-stream";
            context.Response.BinaryWrite(fileBytes);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

参考信息:

  1. http://blog.csdn.net/fanyuna/article/details/5568089
  2. http://www.cnblogs.com/brucejia/archive/2012/12/24/2831060.html
  3. http://www.jb51.net/article/16437.htm
  4. http://tool.oschina.net/commons
That's All.

原文地址:https://www.cnblogs.com/ice-/p/6165786.html