I have a problem. I want to download and view in browser images from a SQL Server table. I don\'t know how to do.
My code:
public partial class IndexForm
You will have to use an HttpHandler
in order to transform back your byte array.
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int id = context.Request.QueryString.Get("ID");
SqlDataReader rdr;
byte[] fileContent = null;
const string connect = @"Server=your_servername;Database=your_database;User
Id=user_id;password=user_password;";
using (var conn = new SqlConnection(connect))
{
var qry = "SELECT FileContent, MimeType, FileName FROM FileStore WHERE ID = @ID";
var cmd = new SqlCommand(qry, conn);
cmd.Parameters.AddWithValue("@ID", id);
conn.Open();
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
rdr.Read();
context.Response.Clear();
context.Response.ContentType = rdr["MimeType"].ToString();
context.Response.BinaryWrite((byte[])rdr["FileContent"]);
context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return true;
}
}
}
Once your image handler is created, register it in your web.config file.
<configuration>
. . .
<system.webServer>
. . .
<handlers>
<add name="ImageHandler" verb="*" path="*.ashx" type="Assembly.ImageHandler,Assembly" />
. . .
</handlers>
</system.webServer>
. . .
</configuration>
Then add the route to ignore in order to handle the file
routes.IgnoreRoute("{handler}.ashx");
Finally, you will be able to display the image by calling it from your html
<img src="~/ImageHandler.ashx?ID=@YourItemId"/>
Regards.