Not able to open .pdf file in IE8 - asp.net

I've posted this question in asp.net web forum but no one replied.
I can't open "ONE" page of .pdf file using IE8 and give me an error message "the file is damaged and could not be repaired" when retrieved from SQL Server 2008, but more than one page I can open with no problem.
With Chrome I can open any number of .pdf pages.
The same page that I can't open using IE8 from DB, can be opened directly from hard disk using IE8.
My code in .asxh file:
context.Response.ContentType = "application/pdf"
Dim strm As Stream = ShowNewsImage(imgName)
If Not strm Is Nothing Then
Dim buffer As Byte() = New Byte(4095) {}
Dim byteSeq As Integer = strm.Read(Buffer, 0, 4096)
Do While byteSeq > 0
context.Response.OutputStream.Write(buffer, 0, byteSeq)
byteSeq = strm.Read(Buffer, 0, 4096)
Loop
context.Response.BinaryWrite(buffer)
End If
Thanks,
Ahmed.

Set Response.buffer to true and response.flush after finishing the PDF.

Seems too obvious but I have to ask... did you try this?
Response.WriteFile(imgName)
Link to documentation in case you're not familiar with this. :)

Proble solved.
I changed the buffer from Object to Byte and it worked !!!
The old code (part of a handler) :
context.Response.ContentType = "application/pdf"
Dim strm As Stream = ShowNewsImage(imgName)
If Not strm Is Nothing Then
Dim buffer As Byte() = New Byte(4095) {}
Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)
Do While byteSeq > 0
context.Response.OutputStream.Write(buffer, 0, byteSeq)
byteSeq = strm.Read(buffer, 0, 4096)
Loop
context.Response.BinaryWrite(buffer)
context.Response.End()
End If
End Sub
Public Function ShowNewsImage(ByVal imgName As String) As Stream
Dim conn As String = ConfigurationManager.ConnectionStrings("Connection").ConnectionString
Dim connection As SqlConnection = New SqlConnection(conn)
Dim sql As String = "SELECT image FROM Table WHERE ID = #ID"
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#ID", imgName)
connection.Open()
Dim img As <strong>Object </strong>= cmd.ExecuteScalar()
Try
Return New MemoryStream(CType(img, Byte()))
Catch
Return Nothing
Finally
connection.Close()
End Try
End Function
As you see, ExecuteScalar() attached the output to an Object.
I changed this to Byte:
context.Response.ContentType = "application/pdf"
Dim buffer As Byte() = New Byte(4095) {}
Dim byteSeq As Integer = 0
Dim conn As String = ConfigurationManager.ConnectionStrings("Connection").ConnectionString
Dim connection As SqlConnection = New SqlConnection(conn)
Dim sql As String = "SELECT image FROM Table WHERE ID = #ID"
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#ID", imgName)
connection.Open()
buffer = cmd.ExecuteScalar()
context.Response.BinaryWrite(buffer)
context.Response.End()
No need to context.Response.OutputStream.Write , it is already impeded in context.Response.BinaryWrite
Took me two days.

Related

Getting The requested FTP command is not supported when using HTTP proxy

I've been at this for days. The GetRequestStream() fails every time, even when set and verified as null. Here is the strange thing, it only happens on 3 out of 5 machines and I can't locate what the difference is. Anybody have a clue?
Public Sub UploadFtpFile_Simple(PushFileName As String)
Me.CreateFile(PushFileName, Me.FetchData())
Dim CompleteFTPPath As String = "ftp://ftp.site.com/Filename.csv"
Dim CompleteLocalPath As String = PushFileName
Dim UName As String = Site1UserName
Dim PWD As String = Site1Pass
Dim reqObj As FtpWebRequest = DirectCast(WebRequest.Create(CompleteFTPPath), FtpWebRequest)
'reqObj.Proxy = GlobalProxySelection.GetEmptyWebProxy()
'reqObj.Proxy = Nothing
'reqObj.Proxy = WebRequest.DefaultWebProxy
'reqObj.Proxy = New System.Net.WebProxy()
reqObj.Method = WebRequestMethods.Ftp.UploadFile
reqObj.Credentials = New NetworkCredential(UName, PWD)
Dim streamObj As FileStream = File.OpenRead(CompleteLocalPath)
Dim buffer(streamObj.Length) As Byte
streamObj.Read(buffer, 0, buffer.Length)
streamObj.Close()
streamObj = Nothing
Try
If DEBUGMODE Then
reqObj.GetRequestStream()
Else
reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)
End If
Console.WriteLine("GetRequestStream Success")
Catch ex As Exception
Console.WriteLine("GetRequestStream failure - {0} Stack Track:{1}", ex.Message, ex.StackTrace)
End Try
reqObj = Nothing
End Sub

Cant open a closed file

I am using the code below to try and open a pdf file and I am getting the error cannot open a closed file? Not sure what I am missing here.
Dim FileName As String
Dim FolderLocation As String = Nothing
Dim FileFormat As String = "application/pdf"
Dim tFileNameArray As Array = Nothing
Dim tFileName As String = Nothing
FileName = "\\Server\Files\45144584.pdf"
Dim fs As New FileStream(FileName, FileMode.Open, FileAccess.Read)
Using (fs)
End Using
Dim data() As Byte = New Byte(fs.Length) {}
Dim br As BinaryReader = New BinaryReader(fs)
br.Read(data, 0, data.Length)
br.Close()
Response.Clear()
Response.ContentType = FileFormat
Response.AppendHeader("Content-Disposition", "attachment; filename=" & tFileName.Split("\")(tFileName.Split("\").Length - 1))
Response.BufferOutput = True
Response.BinaryWrite(data)
Response.End()
You need to have all code that references fs inside of the using, otherwise you are attempting to access an object that has already been disposed. I would also do the same thing with the BinaryReader, since it also implements IDisposable:
Dim data() As Byte
Using fs As New FileStream(FileName, FileMode.Open, FileAccess.Read)
data = New Byte(fs.Length) {}
Using br As New BinaryReader(fs)
br.Read(data, 0, data.Length)
End Using
End Using
...
You have the following lines:
Using (fs)
End Using
After End Using, the file is closed and the fs object disposed of.
You need to put the code that reads from fs inside the using block.
Dim fs As New FileStream(FileName, FileMode.Open, FileAccess.Read)
Using (fs)
End Using
Dim data() As Byte = New Byte(fs.Length) {}
...
You're trying to use fs after it has been disposed. This needs to be:
Dim fs As New FileStream(FileName, FileMode.Open, FileAccess.Read)
Using (fs)
Dim data() As Byte = New Byte(fs.Length) {}
Dim br As BinaryReader = New BinaryReader(fs)
br.Read(data, 0, data.Length)
br.Close()
End Using

Downloading a file from SQL Server - ArgumentOutOfRangeException

I'm trying to download files from an SQL Server 2012 database using GridView. I am getting an ArgumentOutOfRangeException giving me this error:
Index was out of range. Must be non-negative and less than the size of the collection.
on:
Dim fileid As Integer = Convert.ToInt32(GridView1.DataKeys(gvrow.RowIndex).Value.ToString())
Code concerned:
Protected Sub lnkDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Dim fileid As Integer = Convert.ToInt32(GridView1.DataKeys(gvrow.RowIndex).Value.ToString())
Dim name As String, type As String
Dim con As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
con.Open()
Using cmd As New SqlCommand()
cmd.CommandText = "Select content_name, content_type, content_file from content where content_id=#Id"
cmd.Parameters.AddWithValue("#Id", fileid)
cmd.Connection = con
con.Open()
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
download(dt)
End If
End Using
End Sub
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
Protected Sub download(ByVal dt As DataTable)
Dim bytes() As Byte = CType(dt.Rows(0)("Data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows(0)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End Sub
gvrow.RowIndex at time of debugging is 0.
Full Code:
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO
Partial Class Documents
Inherits System.Web.UI.Page
Protected Sub btnUploadContent_Click(sender As Object, e As EventArgs) Handles btnUploadContent.Click
Dim filePath As String = FileUpload.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
Select Case ext
Case ".doc"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".docx"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".xls"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".xlsx"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
Case ".gif"
contenttype = "image/gif"
Exit Select
Case ".pdf"
contenttype = "application/pdf"
Exit Select
End Select
If contenttype <> String.Empty Then
Dim fs As Stream = FileUpload.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "INSERT INTO [master_db].[dbo].[content] ([content_name],[content_type],[content_file]) VALUES (#Name, #ContentType, #Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value() = contenttype
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." + " Upload Image/Word/PDF/Excel formats"
End If
End Sub
Protected Sub lnkDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Dim fileid As Integer = Convert.ToInt32(GridView1.DataKeys(gvrow.RowIndex).Value.ToString())
Dim name As String, type As String
Dim con As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
con.Open()
Using cmd As New SqlCommand()
cmd.CommandText = "Select content_name, content_type, content_file from content where content_id=#Id"
cmd.Parameters.AddWithValue("#Id", fileid)
cmd.Connection = con
con.Open()
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
download(dt)
End If
End Using
End Sub
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
Protected Sub download(ByVal dt As DataTable)
Dim bytes() As Byte = CType(dt.Rows(0)("Data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows(0)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
cmd.CommandType = CommandType.Text
cmd.Connection = conn
Try
conn.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Class
What is happening and why?
replace the error line with this:
Dim selectedRow As Integer = Me.GridView1.CurrentRow.Index
Dim fileid As Integer = Convert.ToInt32(Me.GridView1.Item(1,gvrow.RowIndex).Value.ToString())
Replace the number 1 with the index of the cell that contains the fileid (ie if its the 0 for the first cell, 1 for the second and so on)
Let me know if this works. Am a C# developer so conversions may differ.
pass the RowIndex via CommandArgument and use it to retrieve the DataKey value
add the below line on Button
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
and add the below line on Server Event
Dim Index As Integer = Integer.Parse(e.CommandArgument.ToString())
Dim val As String = DirectCast(Me.grid.DataKeys(Index)("YourDataKeyName"), String)
Update:
See this samples :
sample1
sample 2
I ran into this a while ago myself replacing a predecessors data adapter's with data readers for obvious reasons.
My fix was simple:
if (dt.Rows.Count == 0)
//do stuff
else
//do nothing
GV.DataSource = new DataTable();
you're also loading with a datatable, so that should make deploying it easier.
The reason in your specific case is the exception is thrown when no data is passed to the GV.

Uploading files to SQL Server 2012 with ASP.NET/VB.NET

I followed a tutorial an ran the below code without any errors. The file "uploads", however no data is inserted into my SQL Server table.
Data should be inserted into the content table.
Content Table:
Document.aspx
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO
Partial Class Documents
Inherits System.Web.UI.Page
Protected Sub btnUploadContent_Click(sender As Object, e As EventArgs) Handles btnUploadContent.Click
Dim filePath As String = FileUpload.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
Select Case ext
Case ".doc"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".docx"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".xls"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".xlsx"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
Case ".gif"
contenttype = "image/gif"
Exit Select
Case ".pdf"
contenttype = "application/pdf"
Exit Select
End Select
If contenttype <> String.Empty Then
Dim fs As Stream = FileUpload.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "INSERT INTO content (content_name, content_type, content_file) VALUES (#Name, #ContentType, #Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value() = contenttype
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." + " Upload Image/Word/PDF/Excel formats"
End If
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
cmd.CommandType = CommandType.Text
cmd.Connection = conn
Try
conn.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Class
Can anyone tell me what's going on ?
EDIT: Debug Breakpoint # InsertUpdateData(cmd) :
SqlDbType.Binary Binary {1} System.Data.SqlDbType
+ bytes {Length=4136752} Byte()
+ cmd {System.Data.SqlClient.SqlCommand} System.Data.SqlClient.SqlCommand
+ cmd.Parameters {System.Data.SqlClient.SqlParameterCollection} System.Data.SqlClient.SqlParameterCollection
I have created empty database and added table content just like you have and I used code almost the same as you and it worked fine.
Again, if no exception occurs, please check your connection string and see whether the rows been added to the table in the db specified in connection string.
Here is my code (which is working fine), a bit modified from yours:
Imports System.Data.SqlClient
Imports System.IO
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub btnUploadContent_Click(sender As Object, e As EventArgs) Handles btnTest1.Click
Dim fs As Stream = FileUpload.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "INSERT INTO content (content_name, content_type, content_file) VALUES (#Name, #ContentType, #Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = "filename"
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value() = "jpg"
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim conn As New SqlConnection("Data Source=(local);Initial Catalog=test;Integrated Security=True;")
cmd.CommandType = CommandType.Text
cmd.Connection = conn
Try
conn.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Class
I add sample of SQL to test on DB:
INSERT INTO [master_db].[dbo].[content]
([content_name]
,[content_type]
,[content_file])
VALUES
('test'
,'png'
,0x111111111111111)
SELECT * FROM [master_db].[dbo].[content]
I came across this post looking looking for an example. I used the example code you posted and had the same problem. I found and resolved the following issues and got it working:
I created the db table as pictured. content_type of nchar(5) was the first problem since you were inserting something like "application/vnd.ms-word" which was too big.
The next error was because I had not defined the content_id to be an identity column and since it wasn't listed in the insert statement it failed.
Next I had an error as my db user didn't have insert privileges.
The biggest problem is that the return message was always a success message because even though the InsertUpdateData function was catching errors it was not notifying the calling code. This made me think things were okay. doh! Using a breakpoint on the ExecuteNonQuery allowed me to see the errors.
Hope that helps the next person that stops by....

cannot display image in image control

Its my handler (.ashx)
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else Throw New ArgumentException("No parameter specified") End If
Dim imageData() As Byte = {}
' get the image data from the database using the employeeId Querystring context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Everything is working fine.Only the imageData length is 0 so the image is unable to display.
#Sean: its elsewhr.. here the querystring correctly takes the employeeid passed...
heres the code for db access:
Public Sub bind()
Dim ds1 As New DataSet()
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
con.Open()
Dim query As String = "select * from EmployeeTable"
Dim cmd As New SqlCommand()
Dim da1 As New SqlDataAdapter(query, con)
da1.Fill(ds1, "EmployeeTable")
GridView1.DataSource = ds1.Tables("EmployeeTable")
GridView1.DataBind()
con.Close()
End Sub
You're loading a load of data into the GridView but nothing is being loaded into your imageData variable. So we'll just connect to the database and pull that data out. I'm assuming your image column is called imageData but please change as appropriate.
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then
EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else
Throw New ArgumentException("No parameter specified")
End If
Dim imageData() As Byte = {}
' get the image data from the database using the employeeId Querystring
Using con As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
Using cmd As New SqlCommand("SELECT imageData FROM EmployeeTable WHERE EmployeeID = #EmployeeID", con) 'select imageData column, change column name as appropriate
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID)
Try
con.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
If rdr.Read() Then
imageData = CType(rdr("imageData"), Byte()) 'convert imageData column from result set to byte array and assign to variable
End If
End Using
Catch ex As Exception
'do any error handling here
End Try
End Using
End Using
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Changed the code in the handler to this:
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then
EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else
Throw New ArgumentException("No parameter specified")
End If
Dim Image() As Byte = {}
' get the image data from the database using the employeeId Querystring
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
Dim cmd As New SqlCommand("SELECT Image FROM EmployeeTable WHERE EmployeeID = #EmployeeID", con)
'select imageData column, change column name as appropriate
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID)
Try
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
Image = CType(rdr("Image"), Byte())
'convert imageData column from result set to byte array and assign to variable
End While
Catch ex As Exception
'do any error handling here
End Try
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(Image)
End Sub
Worked for me, may be it will work for you too...

Resources