webcode 发表于 2013-2-7 19:02:48

文件下载时,只弹出下载框,不在页面打开的方法。

default4.aspx:



<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default4.aspx.cs"Inherits="Default4"%>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>无标题页</title>
</head>
<body>
<formid="form1"runat="server">
<div>
<asp:ButtonID="Button1"runat="server"Text="Button"/></div>
</form>
</body>
</html>

default4.aspx.cs:



protectedvoidButton1_Click(objectsender,System.EventArgse)
{
try
{

stringstr="<html>";
for(intpage=0;page<4;page++)
{
str+="<TABLEborderColor='black'cellSpacing='0'borderColorDark='white'cellPadding='3'border='1'>";
str+="<tr><th>描述</th></tr>";
for(inti=1;i<10;i++)
{
str=str+"<tr><td>测试"+i.ToString()+"</td></tr>";

}
str+="</table>";

//.doc换页
str+="<brclear=allstyle='mso-special-character:line-break;page-break-before:always'>";
}

str+="</html>";

byte[]buff=System.Text.Encoding.Unicode.GetBytes(str);
//byte[]buff=System.Text.Encoding.UTF8.GetBytes(str);

byte[]outBuff=newbyte;

//使用文件流方式写入UniCode编码的doc文件。
byte[]mark={0xFF,0xFE};
outBuff=mark;
outBuff=mark;

for(inti=0;i<buff.Length;i++)
{
outBuff=buff;
}

Context.Response.ContentType="application/octet-stream";
stringfileName="测试.doc";
Context.Response.AddHeader("Content-Disposition","attachment;filename=\""+HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8)+"\"");

Context.Response.AddHeader("Content-Length",outBuff.Length.ToString());
Response.BufferOutput=true;
Response.Clear();
Context.Response.BinaryWrite(outBuff);
Context.Response.End();




}
catch(Exceptionex)
{
ex.ToString();
}
finally
{

}

}
在VS2005下调试成功
页: [1]
查看完整版本: 文件下载时,只弹出下载框,不在页面打开的方法。