.Net服務器下發文件

字符串是數據的一種,文件也是,他們的本質都是二進制。在網絡上傳輸時,數據都是流的形式(二進制),因此服務器能返回字符串,也能返回其餘數據類型,主要設置相關HTTP響應頭來完成,話很少說,直接上代碼(.Net)。html

    /// <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.
相關文章
相關標籤/搜索