.net中如何通过gridview跳转页面来实现下载功能
3个回答
展开全部
<asp:TemplateField HeaderText="操作" ItemStyle-HorizontalAlign=Center>
<ItemTemplate>
<asp:LinkButton ID="lbtnDownLoad" runat="server" CommandName="DownLoad" CommandArgument="<%# Bind('文件的虚拟路径') %>" Text="打开" />
</ItemTemplate>
</asp:TemplateField>
在gridview的RowCommand事件中
string rowId = e.CommandArgument.ToString();
case "DownLoad":
this.DownLoad(rowId);
break;
下载函数:
private void DownLoad(string rowId)
{
rowId = rowId.Trim().Replace("/", "/");
string fileName = HttpContext.Current.Server.UrlEncode(rowId.Trim());
string filePath = HttpContext.Current.Server.MapPath(" "+rowId);
//指定块大小
long chunkSize = 102400;
//建立一个100K的缓冲区
byte[] buffer = new byte[chunkSize];
//已读的字节数
long dataToRead = 0;
FileStream stream = null;
try
{
//打开文件
stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
dataToRead = stream.Length;
//添加Http头
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachement;filename=" + fileName);
Response.AddHeader("Content-Length", dataToRead.ToString());
while (dataToRead > 0)
{
if (Response.IsClientConnected)
{
int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
Response.Clear();
dataToRead -= length;
}
else
{
//防止client失去连接
dataToRead = -1;
}
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.Message);
}
finally
{
if (stream != null)
{
stream.Close();
}
Response.Close();
}
}
ok了
<ItemTemplate>
<asp:LinkButton ID="lbtnDownLoad" runat="server" CommandName="DownLoad" CommandArgument="<%# Bind('文件的虚拟路径') %>" Text="打开" />
</ItemTemplate>
</asp:TemplateField>
在gridview的RowCommand事件中
string rowId = e.CommandArgument.ToString();
case "DownLoad":
this.DownLoad(rowId);
break;
下载函数:
private void DownLoad(string rowId)
{
rowId = rowId.Trim().Replace("/", "/");
string fileName = HttpContext.Current.Server.UrlEncode(rowId.Trim());
string filePath = HttpContext.Current.Server.MapPath(" "+rowId);
//指定块大小
long chunkSize = 102400;
//建立一个100K的缓冲区
byte[] buffer = new byte[chunkSize];
//已读的字节数
long dataToRead = 0;
FileStream stream = null;
try
{
//打开文件
stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
dataToRead = stream.Length;
//添加Http头
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachement;filename=" + fileName);
Response.AddHeader("Content-Length", dataToRead.ToString());
while (dataToRead > 0)
{
if (Response.IsClientConnected)
{
int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
Response.Clear();
dataToRead -= length;
}
else
{
//防止client失去连接
dataToRead = -1;
}
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.Message);
}
finally
{
if (stream != null)
{
stream.Close();
}
Response.Close();
}
}
ok了
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询