/// <summary> /// 下载文件 /// 使用流输出 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button1_Click( object sender, System.EventArgs e) { string sFileName = Server.MapPath("./工作用常用电话号码.xls"); FileStream fileStream=new FileStream(sFileName,FileMode.Open); long fileSize = fileStream.Length; byte[] fileBuffer=new byte[fileSize]; fileStream.Read(fileBuffer, 0, (int)fileSize); //如果不写fileStream.Close()语句,用户在下载过程中选择取消,将不能再次下载 fileStream.Close(); Context.Response.ContentType="application/octet-stream"; Context.Response.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(sFileName,Encoding.UTF8 )); Context.Response.AddHeader("Content-Length",fileSize.ToString()); Context.Response.BinaryWrite(fileBuffer); Context.Response.End(); Context.Response.Close(); }
/// <summary> /// 下载文件 /// 直接输出文件方式 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button2_Click( object sender, System.EventArgs e) { string saveFileName = "工作用常用电话号码.xls"; Response.Clear(); Response.Buffer= true; //Response.Charset = "utf-8";//可有可无? //下面两个语句是一个含义,不知网上的人为什么要加一个this,非常的不解! //this.EnableViewState = false; EnableViewState = false; //Response.ContentType = "application/ms-excel"; //可有可无? //Response.ContentEncoding = System.Text.Encoding.UTF8;//可有可无? //直接写下面的语句,客户端看到的文件名是乱码 //Response.AppendHeader("Content-Disposition","attachment;filename=" + saveFileName); //必须写成这种 Response.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(saveFileName,Encoding.UTF8 )); Response.WriteFile(saveFileName); Response.Flush(); Response.End();//End和Close的顺序是什么,测试时,两个位置排列交换后对执行没有任何影响 Response.Close(); }