how create files from database and open them in browser

  • Thread starter Thread starter Daniel Walzenbach
  • Start date Start date
D

Daniel Walzenbach

Hi,

Imagine the following situation: I have an asp.net
application which allows uploading files to a SQL Server
2000 database (Files are stored as type "images"). As a
next step I would like to implement some way to enable
downloading those files from the database which leads me
to the following two problems:
1.) How can I create a file "in memory" as I don't want to
create temporary files stored on my web server and
2.) How can I use the browser (of a person using the
application) to open the files accordingly to their
extensions?

Thank you for your help.
Best regards.
Daniel
 
Hi Daniel,

|| How can I create a file "in memory" as I don't want to
|| create temporary files stored on my web server

Take a look at MemoryStreams - files in memory :-)

System.IO.MemoryStream

Regards,
Fergus
 
Hello,

Daniel Walzenbach said:
Imagine the following situation: I have an asp.net
application which allows uploading files to a SQL Server
2000 database (Files are stored as type "images"). As a
next step I would like to implement some way to enable
downloading those files from the database which leads me
to the following two problems:
1.) How can I create a file "in memory" as I don't want to
create temporary files stored on my web server and

Load the data into a 'MemoryStream' object (namespace 'System.IO').
2.) How can I use the browser (of a person using the
application) to open the files accordingly to their
extensions?

I don't really understand what you want to do. You cannot open every file
type with the browser.
 
Hi,



Thank you both for your answer.

What I'd like to realize is a page with files on it represented as links. If
now somebody clicks on a link there should be the possibility to download
the file and/or open it (Like the dialog you get when you download sth. Let
it be a .doc file and your computer asks you whether you'd like to save it
or open it. The same happens when you download a .exe file. You'll be asked
if you'd like to save or open the file.). The behaviour should be the same
as if somebody is downloading a file from a fileserver but the file should
be generated "of the fly" in the webserver's memory (as it is coming out of
a SQL Server 2000) and then be posted back as if it was a download.



Thank you again for your help. I appreciate your effort.



Daniel
 
Hi Daniel,

I'm researching on the problem, and will update you as soon as I get some
progress.

Would you tell me why you don't want to write it to a temporary file?

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

--------------------
| From: "Daniel Walzenbach" <[email protected]>
| References: <[email protected]>
<#[email protected]>
| Subject: Re: how create files from database and open them in browser
| Date: Tue, 16 Sep 2003 20:47:58 +0200
| Lines: 58
| X-Priority: 3
| X-MSMail-Priority: Normal
| X-Newsreader: Microsoft Outlook Express 6.00.2800.1106
| X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1106
| Message-ID: <[email protected]>
| Newsgroups: microsoft.public.dotnet.languages.vb
| NNTP-Posting-Host: p508bf1bd.dip.t-dialin.net 80.139.241.189
| Path:
cpmsftngxa07.phx.gbl!cpmsftngxa10.phx.gbl!cpmsftngxa06.phx.gbl!TK2MSFTNGP08.
phx.gbl!TK2MSFTNGP11.phx.gbl
| Xref: cpmsftngxa07.phx.gbl microsoft.public.dotnet.languages.vb:137588
| X-Tomcat-NG: microsoft.public.dotnet.languages.vb
|
| Hi,
|
|
|
| Thank you both for your answer.
|
| What I'd like to realize is a page with files on it represented as links.
If
| now somebody clicks on a link there should be the possibility to download
| the file and/or open it (Like the dialog you get when you download sth.
Let
| it be a .doc file and your computer asks you whether you'd like to save it
| or open it. The same happens when you download a .exe file. You'll be
asked
| if you'd like to save or open the file.). The behaviour should be the same
| as if somebody is downloading a file from a fileserver but the file should
| be generated "of the fly" in the webserver's memory (as it is coming out
of
| a SQL Server 2000) and then be posted back as if it was a download.
|
|
|
| Thank you again for your help. I appreciate your effort.
|
|
|
| Daniel
|
|
|
|
Newsbeitrag
| | > Hello,
| >
| > > Imagine the following situation: I have an asp.net
| > > application which allows uploading files to a SQL Server
| > > 2000 database (Files are stored as type "images"). As a
| > > next step I would like to implement some way to enable
| > > downloading those files from the database which leads me
| > > to the following two problems:
| > > 1.) How can I create a file "in memory" as I don't want to
| > > create temporary files stored on my web server and
| >
| > Load the data into a 'MemoryStream' object (namespace 'System.IO').
| >
| > > 2.) How can I use the browser (of a person using the
| > > application) to open the files accordingly to their
| > > extensions?
| >
| > I don't really understand what you want to do. You cannot open every
file
| > type with the browser.
| >
| > --
| > Herfried K. Wagner
| > MVP · VB Classic, VB.NET
| > http://www.mvps.org/dotnet
| >
| >
|
|
|
 
Hey Kevin,

thanks for your help! I have solved the problem thanks to the people in the
thread
how create files from database and open them in browser
[microsoft.public.dotnet.framework.aspnet]. If you need the code (e.g. cause
you are working on a similar problem) just send me an email (without the
..NOSPAM)

Best regards.

Daniel
 
The reply in that group was:

First create a page whose job it is to render an image from the db based on
querystring parameters. See http://www.aspfree.com/print/574,1/print.aspx
for some sample code if you're not sure how to do this.

Once you've got the page set up, you can insert an img tag using the image
page as its source in any other page. e.g.:

<img src="YourImagePage.aspx?<query string parameters to specify which
image>">
 
Hi Fergus,
And you did advise something like
\\\
Dim ms As New MemoryStream(Picture)
Me.Image1 = Image.FromStream(ms)
////
For such a difficult problem.

Reminds me on someone. He did advise the biggest bank cleaner (that is money
exchange between banks) to take 2 small computers.
He was almost fired, because what did think he was, that he could advise
such an important Dutch company such small computers.
That was not his boss who said that, that was computer manager from that
banking company.
Later whole Europe did the exchange with the computers he did advice.

Cor
 
Howdy Cor,

\\\
Dim ms As New MemoryStream(Picture)
Me.Image1 = Image.FromStream(ms) XXX
////

The MemoryStream was only to avoid writing to a file. Me.Image doesn't
exist in this situation.

The hard part of the problem was getting the image data back to the
browser. I had no solution for that one (nor a very similar query when it
occurred a while back - how to download files from a link on a web page when
the files are in a database). Now I know that it's easy - Set the
Response.ContentType to the correct MIME type and BinaryWrite the data.

Cheers,
Fergus
MVP [Windows Start button, Shutdown dialogue]
 
Hi,



what I finally did with the help of you guys was the following (this is the page I redirect users on when they click on a file).



Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

' Hier Benutzercode zur Seiteninitialisierung einfügen

If Not IsPostBack Then

Dim myConnection As New System.Data.SqlClient.SqlConnection



myConnection.ConnectionString = ConfigurationSettings.AppSettings("connstring")



Dim mySelectCommand As New System.Data.SqlClient.SqlCommand



myConnection.Open()



mySelectCommand.Connection = myConnection

mySelectCommand.CommandText = String.Format("select FileName, ContentType, FileData from tblUpload where FileID = {0}", Request.QueryString("Image"))



Dim mySQLDataReader As System.Data.SqlClient.SqlDataReader



mySQLDataReader = mySelectCommand.ExecuteReader



If mySQLDataReader.Read Then



Response.ContentType = mySQLDataReader.Item("ContentType").ToString

Response.BinaryWrite(CType(mySQLDataReader.Item("FileData"), Byte()))

Response.AddHeader("Content-Disposition", String.Format("inline; filename={0}", mySQLDataReader.Item("FileName").ToString))



End If



myConnection.Close()



End If



End Sub



I even could spare the temporary file :-) . Hope this helps everybody who has a similar problem. Thank you for your support!



Best regards



Daniel Walzenbach



P.S. If you need to contact me simply remove ".NOSPAM" from my email address.
 
Hi Daniel and Fergus,
The problem with the given solution was, that the picture shows up as a page, without a button to post back or everything,
You see them often on Internet, the only thing you can do is push on the navigate or close button.
Response.BinaryWrite(CType(mySQLDataReader.Item("FileData"), Byte())

Problem with the binary picture formate is, that there is no webcontrol that will accept an byte())

The solution I is calling a page, that the page himself could get as a picture page via the "session" is the index in the SQL server transported.

With aspx script it is easy, and when you have done it with VB.net language too.

Here it is, I left the cotrols in. I did include the aspx files to at the end.
I have deleted the button for the postback after the picture was shown.

Cor

Option Strict On
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected da As SqlDataAdapter
Protected cbd As SqlCommandBuilder
Protected dsPictures As DataSet
Protected connStr As String = "Server=localhost; DataBase=Northwind; Integrated Security=SSPI"
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Protected WithEvents Image1 As System.Web.UI.WebControls.Image
Protected WithEvents Label1 As System.Web.UI.WebControls.Label
Protected WithEvents ListBox1 As System.Web.UI.WebControls.ListBox
Private designerPlaceholderDeclaration As System.Object

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Dim conn As New SqlConnection(connStr)
Dim cmd As New SqlCommand("SELECT FileName, PictureID FROM Picture", conn)
da = New SqlDataAdapter(cmd)
cbd = New SqlCommandBuilder(da)
dsPictures = New DataSet
da.Fill(dsPictures)
Me.Image1.Visible = False
ListBox1.AutoPostBack = True
Try
ListBox1.DataSource = dsPictures.Tables(0)
ListBox1.DataTextField = "FileName"
ListBox1.DataValueField = "PictureID"
ListBox1.DataBind()
Catch sqlExc As SqlException
Me.Label1.Text = "Database Error" 'sqlExc.ToString
Catch exc As Exception
Me.Label1.Text = "Datbase Connection Failed!"
End Try
conn.Close()
End If
End Sub
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Session.Item("img") = ListBox1.SelectedItem.Value
Image1.Visible = True
Image1.ImageUrl = "http://localhost/testSQLWeb/WebForm2.aspx"
End Sub
End Class

-------------------------
Option Strict On
Imports System.Data.SqlClient
Public Class WebForm2
Inherits System.Web.UI.Page
Protected connStr As String = "Server=localhost; DataBase=Northwind; Integrated Security=SSPI"
#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

End Sub

'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub

#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim conn As New SqlConnection(connStr)
Dim sqlstr As String = String.Format("SELECT Picture FROM Picture WHERE (PictureID = {0})", CInt(Session.Item("img")))
Dim cmd As New SqlCommand(sqlstr, conn)
conn.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
rdr.Read()
Response.BinaryWrite(CType(rdr.Item("Picture"), Byte()))
rdr.Close()
conn.Close()
End Sub
End Class
---------------------------
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="testSQLWeb.WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>WebForm1</title>
<meta content="Microsoft Visual Studio .NET 7.1" name=GENERATOR>
<meta content="Visual Basic .NET 7.1" name=CODE_LANGUAGE>
<meta content=JavaScript name=vs_defaultClientScript>
<meta content=http://schemas.microsoft.com/intellisense/ie5 name=vs_targetSchema>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id=Form1 method=post runat="server"><asp:listbox id=ListBox1 style="Z-INDEX: 103; LEFT: 312px; POSITION: absolute; TOP: 11px" runat="server" Height="122px" Width="285px"></asp:listbox><asp:label id=Label1 style="Z-INDEX: 102; LEFT: 326px; POSITION: absolute; TOP: 352px" runat="server" Height="35px" Width="272px"></asp:label><asp:image id=Image1 style="Z-INDEX: 104; LEFT: 329px; POSITION: absolute; TOP: 143px" runat="server" Height="166px" Width="265px"></asp:image></form>

</body>
</HTML>
-----------------------------------------------------------------------------------------------------------
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm2.aspx.vb" Inherits="testSQLWeb.WebForm2"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>WebForm2</title>
<meta content="Microsoft Visual Studio .NET 7.1" name=GENERATOR>
<meta content="Visual Basic .NET 7.1" name=CODE_LANGUAGE>
<meta content=JavaScript name=vs_defaultClientScript>
<meta content=http://schemas.microsoft.com/intellisense/ie5 name=vs_targetSchema>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id=Form1 method=post
runat="server"></form>

</body>
</HTML>







..








..
 
I made this page again; I saw it was terrible to read.

The problem with the earlier given solution is that the pictures show up as complete pages, without a button to post back or everything. You see them often on Internet, the only thing you can do is push on the navigate button or on the close button.
Response.BinaryWrite(CType(mySQLDataReader.Item("FileData"), Byte())

Problem with the binary picture format is, that there is no webcontrol that will accept a byte())

The solution to solve that problem is calling an other page, that the page that has to show the picture could get as a picture in an image url.

With ASPX script it is easy, and when you have done it with VB.net language too.

Here is it, I left the controls in. I did include the ASPX files at the end.


Cor

Option Strict On
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected da As SqlDataAdapter
Protected cbd As SqlCommandBuilder
Protected dsPictures As DataSet
Protected connStr As String = "Server=localhost; DataBase=Northwind; Integrated Security=SSPI"
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Protected WithEvents Image1 As System.Web.UI.WebControls.Image
Protected WithEvents Label1 As System.Web.UI.WebControls.Label
Protected WithEvents ListBox1 As System.Web.UI.WebControls.ListBox
Private designerPlaceholderDeclaration As System.Object

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Dim conn As New SqlConnection(connStr)
Dim cmd As New SqlCommand("SELECT FileName, PictureID FROM Picture", conn)
da = New SqlDataAdapter(cmd)
cbd = New SqlCommandBuilder(da)
dsPictures = New DataSet
da.Fill(dsPictures)
Me.Image1.Visible = False
ListBox1.AutoPostBack = True
Try
ListBox1.DataSource = dsPictures.Tables(0)
ListBox1.DataTextField = "FileName"
ListBox1.DataValueField = "PictureID"
ListBox1.DataBind()
Catch sqlExc As SqlException
Me.Label1.Text = "Database Error" 'sqlExc.ToString
Catch exc As Exception
Me.Label1.Text = "Datbase Connection Failed!"
End Try
conn.Close()
End If
End Sub
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Session.Item("img") = ListBox1.SelectedItem.Value
Image1.Visible = True
Image1.ImageUrl = "http://localhost/testSQLWeb/WebForm2.aspx"
End Sub
End Class

-------------------------
Option Strict On
Imports System.Data.SqlClient
Public Class WebForm2
Inherits System.Web.UI.Page
Protected connStr As String = "Server=localhost; DataBase=Northwind; Integrated Security=SSPI"
#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

End Sub

'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub

#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim conn As New SqlConnection(connStr)
Dim sqlstr As String = String.Format("SELECT Picture FROM Picture WHERE (PictureID = {0})", CInt(Session.Item("img")))
Dim cmd As New SqlCommand(sqlstr, conn)
conn.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
rdr.Read()
Response.BinaryWrite(CType(rdr.Item("Picture"), Byte()))
rdr.Close()
conn.Close()
End Sub
End Class
---------------------------
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="testSQLWeb.WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>WebForm1</title>
<meta content="Microsoft Visual Studio .NET 7.1" name=GENERATOR>
<meta content="Visual Basic .NET 7.1" name=CODE_LANGUAGE>
<meta content=JavaScript name=vs_defaultClientScript>
<meta content=http://schemas.microsoft.com/intellisense/ie5 name=vs_targetSchema>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id=Form1 method=post runat="server"><asp:listbox id=ListBox1 style="Z-INDEX: 103; LEFT: 312px; POSITION: absolute; TOP: 11px" runat="server" Height="122px" Width="285px"></asp:listbox><asp:label id=Label1 style="Z-INDEX: 102; LEFT: 326px; POSITION: absolute; TOP: 352px" runat="server" Height="35px" Width="272px"></asp:label><asp:image id=Image1 style="Z-INDEX: 104; LEFT: 329px; POSITION: absolute; TOP: 143px" runat="server" Height="166px" Width="265px"></asp:image></form>

</body>
</HTML>
-----------------------------------------------------------------------------------------------------------
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm2.aspx.vb" Inherits="testSQLWeb.WebForm2"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>WebForm2</title>
<meta content="Microsoft Visual Studio .NET 7.1" name=GENERATOR>
<meta content="Visual Basic .NET 7.1" name=CODE_LANGUAGE>
<meta content=JavaScript name=vs_defaultClientScript>
<meta content=http://schemas.microsoft.com/intellisense/ie5 name=vs_targetSchema>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id=Form1 method=post
runat="server"></form>

</body>
</HTML>
 
Back
Top