Yon*_*oni 5 c# asp.net webforms download
在ASP.Net(使用C#)中,我正在尝试使用纯文本创建一个.DAT文件并将其发送到浏览器并强制下载.我尝试了几件事,但我无法让它发挥作用.在我的aspx文件中有一个ImageButton
<asp:ImageButton ID="btnSave" runat="server" CausesValidation="False" ImageUrl="~/Images/Stages/Database/Save.png" OnClick="btnSave_OnClick" Width="26px" />
Run Code Online (Sandbox Code Playgroud)
在OnClick方法中,我正在尝试创建文件并将其发送到浏览器.
protected void btnSave_OnClick(object sender, EventArgs e)
{
string file = "test.dat";
string fileName = "~\\Stages\\Broekx\\Databanken\\" + file;
FileStream fs = new FileStream(MapPath(fileName), FileMode.Open);
long cntBytes = new FileInfo(MapPath(fileName)).Length;
byte[] byteArray = new byte[Convert.ToInt32(cntBytes)];
fs.Read(byteArray, 0, Convert.ToInt32(cntBytes));
fs.Close();
ImageButton btnSave = (ImageButton)FormViewStagesDummy.FindControl("btnSave");
btnSave.Visible = false;
File.Delete(Server.MapPath(fileName));
if (byteArray != null)
{
this.Response.Clear();
this.Response.ContentType = "text/plain";
this.Response.AddHeader("content-disposition", "attachment;filename=" + file);
this.Response.BinaryWrite(byteArray);
this.Response.End();
this.Response.Flush();
this.Response.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
文件test.dat存在于正确的文件夹中,在读入字节后必须删除.我试过这个没有删除文件,也不会工作.
单击btnSave后,必须隐藏按钮,这就是我将参数Visible设置为false的原因.
我也尝试过内容类型"application/octet-stream"或PDF文件和内容类型"application/pdf",但没有任何效果.页面正常加载,没有下载文件.
文件字符串的路径真的正确吗?
this.Response.AddHeader("content-disposition", "attachment;filename=" + file);
Run Code Online (Sandbox Code Playgroud)
不应该是文件名吗?
为什么要在将文件写入响应之前删除该文件?通过响应提供文件然后删除它不是更有意义吗?
即打电话
File.Delete(Server.MapPath(fileName));
Run Code Online (Sandbox Code Playgroud)
得到回应后。
你应该试试:
Response.TransmitFile( Server.MapPath(fileName) );
Response.End();
Run Code Online (Sandbox Code Playgroud)
TransmitFile 非常高效,因为它基本上将文件流卸载到 IIS,包括可能导致文件缓存在内核缓存中(基于 IIS 的缓存规则)。响应.End();
| 归档时间: |
|
| 查看次数: |
8490 次 |
| 最近记录: |