Link to home
Start Free TrialLog in
Avatar of M.L. Martin
M.L. MartinFlag for United States of America

asked on

Retrieve stored Word, PDF or Excel binary file from SQL Server 2008 database and display to user

I have worked through the development process and I can now upload a document or image and store it to a SQL 2008 database. The image is stored in a field of type varbinary (MAX). My final step is I will supply a user with another asp.net page. A link will display in a gridview or something similar. I will allow the user to pass the value to the final page and that is where I want to display the Word, PDF or Excel document. I am hoping that I can open the document within the browser but I will also be ok if the user has to save before opening. The strong preference by the business community is to open directly and through the browser. I am very, very new to ASP.Net. Luckily I am doing this application in .Net 4 (Visual Studio 2010) so much of the code needed has been generated. I am not the best code writer in the world so any help as always is very appreciated. I have seen only pieces of examples of displaying when it's an image but not a binary like a PDF.
ASKER CERTIFIED SOLUTION
Avatar of lazyberezovsky
lazyberezovsky
Flag of Belarus image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of M.L. Martin

ASKER

Thanks lazyberezovsky. However, I think this is a C# solution. I need a VB.net solution.
No problem. It's .Net
For future: http://converter.telerik.com/

And add VB.Net zone to question, when VB code expected :)
Dim connectionString As String
' Get connection string.
Dim insertCommandText As String
' E.g. INSERT INTO TableName VALUES (@file)
Dim fileName As String
' File to be saved.
Using conn As New SqlConnection(connectionString)
	Using cmd As New SqlCommand(insertCommandText, conn)
		cmd.Parameters.Add(New SqlParameter("@file", File.ReadAllBytes(fileName)))
		conn.Open()
		cmd.ExecuteNonQuery()
	End Using
End Using

' Reading *.doc from database (and writing to response):
Dim connectionString As String
Dim selectCommandText As String
Dim fileName As String

Using conn As New SqlConnection(connectionString)
	Using cmd As New SqlCommand(selectCommandText, conn)
		conn.Open()

		Using writer As New BinaryWriter(Response.OutputStream)
			writer.Write(DirectCast(cmd.ExecuteScalar(), Byte()))
		End Using

		Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName)
		Response.ContentType = "application/ms-word"
		Response.[End]()
	End Using
End Using

Open in new window