下载文本从网页文件 [英] Download text as a file from a webpage

查看:154
本文介绍了下载文本从网页文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下载从一个网站的文字和我想要让用户可以将其保存为一个文件。所以,我有以下的code,它做到了这一点。

I'm downloading text from a website and I want to have the user be able to save it as a file. So, I have the following code that does just that.

protected void DownloadFile(string fileName, string content)
{
    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.ContentType = "text/plain";
    Response.Write(content);
    Response.End();
}

我遇到的问题是,我得到这个code运行后异常。我相信这是由于这样的事实,我打电话到Response.End()。所以,每一次用户下载它会将其重定向到一般性的错误页面的文件,因为所有的通用例外重定向到该页面。

The problem I am having is that I get an exception after this code runs. I believe it's due to the fact that I call Response.End(). So, every time a user downloads a file it redirects them to the generic error page because all generic exceptions redirect to that page.

我如何能写出来的文字到一个文件中,并没有得到这个错误任何想法?如果我删除到Response.End()我得到我的文字,然后Htt的presponse文字的休息,但我不明白的错误。

Any ideas on how I can write text out to a file and not get this error? If I remove Response.End() I get my text and then the rest of the HttpResponse text, but I don't get the error.

感谢。

推荐答案

不要叫到Response.End()。还有code来运行服务器端已填充你是否有意与否头后。相反,考虑使用 Response.Flush()并允许页面来完成。另一种方法是使用一个HttpHandler的(ASHX)文件,而不是一个aspx / ascx的文件。这会给你的回应更基本的访问,所以你应该能够结束没有反响。

Don't call Response.End(). There is still code to be run server-side after you have populated the headers whether you intend to or not. Instead consider using Response.Flush() and allowing the page to complete. Another alternative would be to use a HttpHandler (ashx) file instead of an aspx/ascx file. This will give you more basic access to the Response so you should be able to end without repercussion.

这篇关于下载文本从网页文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆