[英]File download from database not working
我繼承了這個網站,並在文件下載方面遇到了問題。 諸如.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();
}
}
我要對此進行說明,說您需要將Anchor
標簽更改為以下內容:
<a href='<%# Page.ResolveUrl("~/UserControls/FileFetch.ashx?fileId=" + Convert.ToString(Eval("fileId"))) %>' target="_blank">
指向Page.ResolveUrl
方法的MSDN鏈接在此處 。 頁面繼承自Control,因此為什么鏈接引用Control.ResolveUrl。
我剛剛看到另一種替代方法是將runat="server"
添加到Anchor
標記中,以將其轉變為服務器控件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.