我是.Net开发的新手。 我尝试启用下载txt文件:
我使用此代码:
protected void Page_Load(object sender, EventArgs e)
{
string str = "Test information";
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
MemoryStream mem = new MemoryStream();
mem.Write(bytes, 0, str.Length);
Stream outStream = Response.OutputStream;
Response.ContentType = "application/text/plain";
Response.AppendHeader("Connection", "keep-alive");
Response.AppendHeader("Content-Disposition", " attachment; filename = " + "test.txt");
mem.WriteTo(outStream);
outStream.Close();
}
但是我得到的文本文件包含错误的第一个字符串(编码问题)和许多其他字符串以及当前页面的信息。
更新 这是我得到的文件
Bad string
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head><title>
ASP.NET AJAX Web Services: Web Service Sample Page
</title>
<script src="../Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#MainContent_RegisterUser_CreateUserStepContainer_UserName").blur(function (event) {
$.ajax({
type: "POST",
url: "../About.aspx/validateUser",
contentType: "application/json; charset=utf-8",
data: "{'username': '" + $(this).val() + "'}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
});
function AjaxSucceeded(result) {
if (result.d == "true") {
$("#LoginSpan").text("Такой пользователь уже существует");
}
else {
$("#LoginSpan").text("");
}
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
</script>
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form method="post" action="BuyingSuccess.aspx?id=19" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE1MjQ5ODA0NjlkGAIFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYCBSljdGwwMCRIZWFkTG9naW5WaWV3JEhlYWRMb2dpblN0YXR1cyRjdGwwMQUpY3RsMDAkSGVhZExvZ2luVmlldyRIZWFkTG9naW5TdGF0dXMkY3RsMDMFE2N0bDAwJEhlYWRMb2dpblZpZXcPD2QCA2THchHerzY1rr1yLcH18X4YPCuH2pX6++6OU9oOftLDQg==" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/Shop3/WebResource.axd?d=gJqNbXOsVujM8wR8-hfUcLtWhOiTVJCVfh9Lo7jgFFHsWxINU3DVAgCd3VVMHS94GhZGb8YTI_r4HUkshGHWuB2iNiNOHXsKESFMdk577mE1&t=634669639690714017" type="text/javascript"></script>
<div class="aspNetHidden">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgL4/Z3vDgLC0ZzyCk29Agd/VrCau7HXz2AM6rx2j8z5dvoBoXKKKc+infsA" />
</div>
<div class="page">
<div class="header">
<div class="title">
<h1>
Рнструкции
</h1>
</div>
<div class="loginDisplay">
<span class="bold">
<span id="HeadLoginView_HeadLoginName">usert</span>
</span>
<a id="HeadLoginView_HeadLoginStatus" href="javascript:__doPostBack('ctl00$HeadLoginView$HeadLoginStatus$ctl00','')">Выйти</a>
</div>
<div class="clear hideSkiplink">
<a href="#NavigationMenu_SkipLink"><img alt="Skip Navigation Links" src="/Shop3/WebResource.axd?d=qlxWJrbukMv20w9xY1h0SQe9L8dtSGVTDQ606-0jsJTHpyJh9XQcnnSaKyQTCktjR9G7_qlWhTXAgZB4Ay9LLv-RUiwbYud3LVU-Sm9I6hQ1&t=634669639690714017" width="0" height="0" style="border-width:0px;" /></a><div class="menu" id="NavigationMenu">
<ul class="level1">
<li><a class="level1" href="Default.aspx">Рнструкции</a></li><li><a class="level1" href="About.aspx">Рћ проекте</a></li>
</ul>
</div><a id="NavigationMenu_SkipLink"></a>
</div>
</div>
<div class="main">
<span id="MainContent_Label1">Вы купили инструкцию, поздравляем!</span>
</div>
<div class="clear">
</div>
</div>
<div class="footer">
</div>
<script type='text/javascript'>new Sys.WebForms.Menu({ element: 'NavigationMenu', disappearAfter: 500, orientation: 'horizontal', tabIndex: 0, disabled: false });</script></form>
</body>
</html>
如何解决此问题?
答案 0 :(得分:1)
将ContentType更改为application/octet-stream
,以确保通过所有浏览器下载文件。
例如将其更改为:
Response.Clear();
Response.Charset = "";
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.ContentType = "application/octet-stream";
Response.Write(mem.ToArray());
Response.End();
答案 1 :(得分:0)
在outStream.Close()之后在Page_load事件的末尾添加以下行;声明
Response.End();
答案 2 :(得分:-1)
也许这也是使用System.Net.WebClient从Web资源下载字符串,字节或文件的好方法。
WebClient client = new WebClient();
byte[] imageAsBytes = client.DownloadData(uri);
String webSource = client.DownloadString(uri);
client.DownloadFile(uri, "C:\\myfile.txt");
它还支持异步下载。