在ASP.NET中将文本下载为文件

cqoc49vn  于 5个月前  发布在  .NET
关注(0)|答案(2)|浏览(86)

我试图下载一些文本输出从屏幕上作为一个文本文件.下面是代码.它的工作在某些网页和不工作在所有其他网页.有人可以请建议什么是错在这里?

protected void Button18_Click(object sender, EventArgs e){
    Response.Clear();
    Response.Buffer = true;
    Response.ContentType = "text/plain";
    Response.AppendHeader("content-disposition", "attachment;filename=output.txt");

    StringBuilder sb = new StringBuilder();
    string output = "Output";
    sb.Append(output);
    sb.Append("\r\n");
    Response.Write(sb.ToString());
}

字符串

mwg9r5ms

mwg9r5ms1#

正如约书亚已经提到的,您需要将文本写入输出流(使用Response对象)。此外,不要忘记在此之后调用Response.End()

protected void Button18_Click(object sender, EventArgs e)
{
    StringBuilder sb = new StringBuilder();
    string output = "Output";
    sb.Append(output);
    sb.Append("\r\n");
    
    string text = sb.ToString();
    
    Response.Clear();
    Response.ClearHeaders();

    Response.AppendHeader("Content-Length", text.Length.ToString());
    Response.ContentType = "text/plain";
    Response.AppendHeader("Content-Disposition", "attachment;filename=\"output.txt\"");

    Response.Write(text);
    Response.End();
}

字符串
编辑1:添加更多细节
编辑2:我阅读了其他SO帖子,其中用户建议在文件名周围加上引号:

Response.AppendHeader("content-disposition", "attachment;filename=\"output.txt\"");


来源:https://stackoverflow.com/a/12001019/558486

dba5bblo

dba5bblo2#

如果这是您的实际代码,则您永远不会将文本写入响应流,因此浏览器永远不会接收任何数据。
至少你需要

Response.Write(sb.ToString());

字符串
将文本数据写入响应。此外,作为额外的奖励,如果您事先知道长度,则应使用Content-Length头提供它,以便浏览器可以显示下载进度。
您也将Response.Buffer = true;设置为方法的一部分,但从未显式刷新响应以将其发送到浏览器。请尝试在write语句后添加Response.Flush()

相关问题