我继承了这个网站并且存在文件下载问题。 .pdf,.doxs,.txt等文件作为映像保存在Sql中。数据列表控件与a href
控件一起使用以查看/下载它但它不起作用。我意识到a href
控件不适合使用,但不确定使用什么控件。
这是aspx标记:
<asp:DataList ID="DataList2" runat="server" DataSourceID="SqlDataSource2" DataKeyField="fileId">
<ItemTemplate>
<a href='<%# "~/UserControls/FileFetch.ashx?fileId=" + Convert.ToString(Eval("fileId")) %>' target="_blank">
<%# Convert.ToString(Eval("fileName"))%></a>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ClubSiteDB %>"
SelectCommand="SELECT [fileId], [fileName], [postedBy] FROM [FilesLibrary]">
</asp:SqlDataSource>
一个名为FileFetch.ashx的帮助文件用于获取文件:
<%@ WebHandler Language="C#" Class="FileFetch" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.IO;
public class FileFetch : IHttpHandler
{
const int BUFFERSIZE = 1024;
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
response.ContentType = "response.ContentType";
response.Cache.SetCacheability(HttpCacheability.Public);
response.BufferOutput = false;
writeSingleImage(Convert.ToInt32(request.QueryString["fileId"]), response.OutputStream);
response.End();
}
public void writeSingleImage(int fileId, Stream output)
{
string cxnstr = System.Configuration.ConfigurationManager.ConnectionStrings["ClubSiteDB"].ConnectionString;
SqlConnection connection = new SqlConnection(cxnstr);
string query;
query = "SELECT fileData FROM dbo.FilesLibrary where fileId=@fileId";
SqlCommand command = new SqlCommand(query, connection);
SqlParameter param0 = new SqlParameter("@fileId", SqlDbType.Int);
param0.Value = fileId;
command.Parameters.Add(param0);
connection.Open();
byte[] d = ((byte[])(command.ExecuteScalar()));
output.Write(d, 0, d.Length);
connection.Close();
}
}
答案 0 :(得分:1)
我将对此进行一次尝试,并说您需要将Anchor
标记更改为以下内容:
<a href='<%# Page.ResolveUrl("~/UserControls/FileFetch.ashx?fileId=" + Convert.ToString(Eval("fileId"))) %>' target="_blank">
Page.ResolveUrl
方法的MSDN链接为here。页面从Control继承,因此链接引用Control.ResolveUrl的原因。
我刚刚看到另一种方法是将runat="server"
添加到Anchor
标记,以将其转换为服务器控件。