方法一:以二进制流的形式下载
string fileName = this.nameSave.Value;//客户端保存的文件名 //以字符流的形式下载文件 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 FileName = "文件名.xls"; Response.Clear(); Response.Buffer = true; EnableViewState = false; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)); Response.WriteFile(FileName); Response.Flush(); Response.Close(); Response.End();