C# 在GridView里面使用a标签下载文件(图片)
2024-10-21 11:49:24
不能使用ajax进行下载文件的操作,具体原因需百度
前端页面,在GridView里面使用模板列,模板列放a标签
<cimesui:cimesGridView ID="GridView1" runat="server" AutoGenerateColumns="False" CssClass="left"
DataKeyNames="ID" OnRowDataBound="GridView1_RowDataBound" OnRowDeleted="GridView1_RowDeleted"
OnRowDeleting="GridView1_RowDeleting" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:CommandField HeaderText="操作" ShowDeleteButton="True" >
<ItemStyle HorizontalAlign="Center" />
</asp:CommandField>
<asp:TemplateField HeaderText="" HeaderStyle-Width="200px">
<ItemTemplate>
<a href="javascript:;" onclick="return GetSelectedRow(this)">下载</a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="filename" HeaderText="文件名" />
<asp:BoundField DataField="filesize" DataFormatString=" {0} Byte" HeaderText="文件尺寸">
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
</Columns>
<EmptyDataTemplate>
没有附档存在!
</EmptyDataTemplate>
</cimesui:cimesGridView>
//前端页面的GetSelectedRow方法
<script type="text/javascript">
//获取选中行的ID,并打开一般处理程序页面
function GetSelectedRow(UserLink) {
var row = UserLink.parentNode.parentNode;
var id = row.cells[2].innerHTML;
window.location.href = "../Function/IQCGetUploadFile.ashx?id=" + id+"";
}
</script>
//一般处理程序(后缀名.ashx) IQCGetUploadFile.ashx 页面代码 public class IQCGetUploadFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try {
//string ID = context.Request["id"].ToString();
string ID = context.Request.QueryString["id"];
string filePath = InspectDAC.GetFilePath(ID);
string fileName = filePath.Substring(filePath.LastIndexOf('\\')).Substring(1); byte[] output = InspectDAC.OutputAttachmentFile(ID);
//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
HttpContext.Current.Response.Clear();
fs.Close();
HttpContext.Current.Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.WriteFile(filePath);
HttpContext.Current.Response.Flush();
//context.Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
} catch (Exception ex)
{
context.Response.Write(ex.Message);
} } public bool IsReusable
{
get
{
return false;
}
}
}
最新文章
- 百度echarts
- 利用cubieboard设置samba打印服务器
- VIew中的触摸事件 touchBegin 等一系列方法
- 最常见的HTTP错误
- poj 2488A Knight&#39;s Journey
- codevs1906 最长递增子序列问题
- ASP.NET简单文件上传
- 理解ThreadLocal(一)
- pro asp.net mvc 5笔记
- Activity绑定自定义视图
- sql面试总结
- Codeforces Round #129 (Div. 1)E. Little Elephant and Strings
- Javascript 京东轮播图
- HTTP lab01 做一个简单的测试用 web页面
- 题解-hzy loves segment tree I
- HttpClient实现HTTP文件通用下载类
- js 高级知识点
- Leetcode 题解 Jump Game
- apache的80端口被占用
- Java 如何重写对象的 equals 方法和 hashCode 方法