HI!
I am searching now a real long time in the forum and I found a lot of stuff to this topic. But please help me it doesn't work!
On my webapplication there is a possibility to save a private picture.
If a new user is saved in the database I want to save a fixed picture as startpicture.
Dim picturePath As String = Request.ServerVariables("APPL_PHYSICAL_PATH") & "img\anonymous.jpg"Please tell me the way how to save this anonymous.jpg from the picturePath into the database and after that how to display the picture.
Thank you!
.
![]() |
0 |
![]() |
I'm not that clued up, but I know you must use BLOB (binary large object) datafield in your sql table. Maybe if you run a search on that topic you should come right...
Here is a nice link
http://www.codersource.net/csharp_read_write_images_database.aspx
![]() |
0 |
![]() |
Thank you. I will try this. My database is not the problem.
If anyone has a little more details to my example and not links to some other sites I will be very happy (its not so easy for me to figure that out - there is never a single file - it is always a uploadfile-component or something).
Thank you very much for more help!
![]() |
0 |
![]() |
Stefan
I also need to do this soon, will let you know if I have any luck...
![]() |
0 |
![]() |
Hi..below code if for saving the image in the sqldatabase in the image column..
try like this u get it.
Recently i tried for uploding image
aspx code is
<body style="font: 10pt verdana">
<form id="Form1" enctype="multipart/form-data" runat="server">
<asp:Table ID="Table1" Runat=server Width=50% BorderWidth=1 BackColor=Beige>
<asp:TableRow>
<asp:TableCell ColumnSpan=2 BackColor="#ff0000">
<asp:Label ID="Label1" Font-Name="verdana" Font-size="12px" ForeColor="#ffffff" font-bold="True" Runat=server Text="Add New Person" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell HorizontalAlign="Right"><asp:Label ID="Label2" Font-Name="verdana" Font-size="12px" Runat=server Text="Name" /></asp:TableCell>
<asp:TableCell><asp:TextBox id=txtPersonName Runat=server /></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell HorizontalAlign="Right"><asp:Label ID="Label3" Font-Name="verdana" Font-size="12px" Runat=server Text="Email" /></asp:TableCell>
<asp:TableCell><asp:TextBox id="txtPersonEmail" Runat=server /></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell HorizontalAlign="Right"><asp:Label ID="Label4" Font-Name="verdana" Font-size="12px" Runat=server Text="Sex" /></asp:TableCell>
<asp:TableCell>
<asp:RadioButton GroupName="sex" Font-Name="Verdana" Font-Size="12px" Text="Male" ID="sexMale" Runat=server />
<asp:RadioButton GroupName="sex" Font-Name="Verdana" Font-Size="12px" Text="FeMale" ID="sexFeMale" Runat=server />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell HorizontalAlign="Right"><asp:Label ID="Label5" Font-Name="verdana" Font-size="12px" Runat=server Text="Date Of Birth" /></asp:TableCell>
<asp:TableCell><asp:TextBox id="txtPersonDOB" Runat=server /></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell HorizontalAlign="Right"><asp:Label ID="Label6" Font-Name="verdana" Font-size="12px" Runat=server Text="Image" /></asp:TableCell>
<asp:TableCell><input type="file" id="PersonImage" runat=server /></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell ColumnSpan=2 HorizontalAlign=Center>
<asp:Button ID="Button2" Text="Add Person" Runat=server />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
<asp:Button ID="Button1" runat="server" Style="z-index: 100; left: 352px; top: 173px" Text="Button" />
</form>
</body>
and server code for this is
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim intImageSize As Int64
Dim cnn As Data.SqlClient.SqlConnection
Dim strImageType As String
Dim ImageStream As Stream
' Gets the Size of the Image
intImageSize = PersonImage.PostedFile.ContentLength
' Gets the Image Type
strImageType = PersonImage.PostedFile.ContentType
' Reads the Image
ImageStream = PersonImage.PostedFile.InputStream
Dim ImageContent(intImageSize) As Byte
Dim intStatus As Integer
intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
' Create Instance of Connection and Command Object
'Dim conn As SqlConnection(Configuration.ConfigurationManager.AppSettings("SqlConnectionString"))
'conn = New SqlConnection(Configuration.ConfigurationManager.AppSettings("SqlConnectionString"))
Dim conn As String = "SERVER=localhost;UID=sa;PWD=;Initial Catalog=saa;Connection Lifetime=30"
cnn = New Data.SqlClient.SqlConnection(conn)
'Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim myCommand As New SqlCommand("sp_person_isp", cnn)
' Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure
' Add Parameters to SPROC
Dim prmEmail As New SqlParameter("@PersonEmail", SqlDbType.VarChar, 255)
prmEmail.Value = txtPersonEmail.Text
myCommand.Parameters.Add(prmEmail)
Dim prmName As New SqlParameter("@PersonName", SqlDbType.VarChar, 255)
prmName.Value = txtPersonName.Text
myCommand.Parameters.Add(prmName)
Dim prmSex As New SqlParameter("@PersonSex", SqlDbType.Char, 1)
If sexMale.Checked Then
prmSex.Value = "M"
Else
prmSex.Value = "F"
End If
myCommand.Parameters.Add(prmSex)
Dim prmPersonDOB As New SqlParameter("@PersonDOB", SqlDbType.DateTime)
prmPersonDOB.Value = txtPersonDOB.Text
myCommand.Parameters.Add(prmPersonDOB)
Dim prmPersonImage As New SqlParameter("@PersonImage", SqlDbType.Image)
prmPersonImage.Value = ImageContent
myCommand.Parameters.Add(prmPersonImage)
Dim prmPersonImageType As New SqlParameter("@PersonImageType", SqlDbType.VarChar, 255)
prmPersonImageType.Value = strImageType
myCommand.Parameters.Add(prmPersonImageType)
Try
cnn.Open()
myCommand.ExecuteNonQuery()
cnn.Close()
Response.Write("New person successfully added!")
Catch SQLexc As SqlException
Response.Write("Insert Failed. Error Details are: " & SQLexc.ToString())
End Try
End Sub
Database table is like this
Drop Table Person
Go
Create Table Person
(
PersonID Int Identity,
PersonEmail Varchar(255),
PersonName Varchar(255),
PersonSex Char(1),
PersonDOB DateTime,
PersonImage Image,
PersonImageType Varchar(255)
)
Drop Proc sp_person_isp
Go
Create Proc sp_person_isp
@PersonEmail Varchar(255),
@PersonName Varchar(255),
@PersonSex Char(1),
@PersonDOB DateTime,
@PersonImage Image,
@PersonImageType Varchar(255)
As
Begin
Insert into Person
(PersonEmail, PersonName, PersonSex,
PersonDOB, PersonImage, PersonImageType)
Values
(@PersonEmail, @PersonName, @PersonSex,
@PersonDOB, @PersonImage, @PersonImageType)
End
Go
![]() |
0 |
![]() |
Thank you!! I will try this.
Do you have an example how you are displaying the image, too?
![]() |
0 |
![]() |
Hi,
Based on my understanding, you want to achieve writing/retrieving the image from the database and display it on the page.
There is a sample as below. You can try it.
Firstly, you need write the image into database first.
public void OnUpload(Object sender, EventArgs e) { // Create a byte[] from the input file int len = Upload.PostedFile.ContentLength; byte[] pic = new byte[len]; Upload.PostedFile.InputStream.Read (pic, 0, len); // Insert the image and comment into the database SqlConnection connection = new SqlConnection (@"connection string"); try { connection.Open (); SqlCommand cmd = new SqlCommand ("insert into table " + "(id, img) values (@id, @img)", connection); cmd.Parameters.Add ("@img", pic); cmd.Parameters.Add ("@id", Comment.Text); cmd.ExecuteNonQuery (); } finally { connection.Close (); } }The below codes can retrieve all the images from the database and display on the image controls which are created dynamically. Handler.ashx will retrieve the images and write to the client. showpic.aspx will display the image from Handler.ashx on the image control.
showpic.aspx:
string constr = @"your connection string"; SqlConnection connection = new SqlConnection(constr); SqlDataAdapter sda = new SqlDataAdapter("select * from table", connection); DataTable dt= new DataTable(); sda.Fill(dt); for (int i = 0; i < dt.Rows.Count; i++) { Image ib = new Image(); ib.ID = "image"+i.ToString(); ib.ImageUrl = "Handler.ashx?PhotoID=" +dt.Rows[i]["id"].ToString(); Page.Controls.Add(ib); }Create Handler.ashx(Generic Handler file)
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Data; using System.Data.SqlClient; using System.IO; using System.Web; using System.Configuration; public class Handler : IHttpHandler { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { // Set up the response settings context.Response.ContentType = "image/jpeg"; context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.BufferOutput = false; int photoId = -1; Stream stream = null; if (context.Request.QueryString["PhotoID"] != null && context.Request.QueryString["PhotoID"] != "") { photoId = Convert.ToInt32(context.Request.QueryString["PhotoID"]); stream = GetPhoto(photoId); } const int buffersize = 1024 * 16; byte[] buffer = new byte[buffersize]; int count = stream.Read(buffer, 0, buffersize); while (count > 0) { context.Response.OutputStream.Write(buffer, 0, count); count = stream.Read(buffer, 0, buffersize); } } public Stream GetPhoto(int photoId) { SqlConnection myConnection = new SqlConnection( ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); SqlCommand myCommand = new SqlCommand ("SELECT img FROM table WHERE id=@PhotoID", myConnection); myCommand.CommandType = CommandType.Text; myCommand.Parameters.Add(new SqlParameter("@PhotoID", photoId)); myConnection.Open(); object result = myCommand.ExecuteScalar(); try { return new MemoryStream((byte[])result); } catch (ArgumentNullException e) { return null; } finally { myConnection.Close(); } } }About ashx:
You can also use aspx instead. It's ok.
The ashx won't create HTML code but aspx will. So response.write some stream into ashx is more efficacious than in aspx.
You can check this link to know about ashx http://cs.jaxdug.com/blogs/dennisbottjer/archive/2005/06/20/730.aspx
Hope it helps.
Vince Xu
Microsoft Online Community Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
![]() |
0 |
![]() |
Vince Xu - MSFT:
int len = Upload.PostedFile.ContentLength; byte[] pic = new byte[len]; Upload.PostedFile.InputStream.Read (pic, 0, len);Hi Vince! I think there is all I need. One last question. Do you know how I could come to same result (image as byte) if I want to use a fixed filepath (c:\web\img\anonymous.jpg) instead of a FileUpload-component?
Thank you so much!
![]() |
0 |
![]() |
Sorry, please forget the question before. My real problem is:
Vince Xu - MSFT:
Page.Controls.Add(ib);Is there another way to bind the picture? If I do like that the picture is always the last thing on the site.
I tried to bind it on an ASP-Image-Control like that:
imPhoto.ImageUrl = ("Handler.ashx?PhotoID=" + value)
imPhoto.Databind()But this is not working only the Page.Controls.Add loads the picture.
I also tried Placeholder1.Controls.Add but this is not working.Please help me a last time!!
The question before I solved like that:
Dim picturePath As String = Request.ServerVariables("APPL_PHYSICAL_PATH") & "img\anonymous.jpg"
Dim finfo As IO.FileInfo = New IO.FileInfo(picturePath)
Dim len As Long = finfo.Length
Dim fStream As IO.FileStream = New IO.FileStream(picturePath, IO.FileMode.Open, IO.FileAccess.Read)
Dim br As IO.BinaryReader = New IO.BinaryReader(fStream)
Dim FileByteArray As Byte()
FileByteArray = br.ReadBytes(CInt(len))And FileByteArray i save to the image-field in my DB.
![]() |
0 |
![]() |
Hi,
Page.Controls.Add(ib) is not about binding. It will add image one by one by retireve the image from the database.
Besides it, you can retrieve several images from database into GridView/Repeater/DataList at one time which is about bind.
In the below codes, it'll bind the Repeater control with the data from database, and image control will catch the image via Handler.ashx. Rather than using Image.DataBind().
<asp:Repeater ID="Repeater1" runat="server"
DataSourceID="SqlDataSource1" >
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl='<%# "Handler.ashx?PhotoID=" + Eval("ID") %>' runat="server" />
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT ID FROM [photo]"></asp:SqlDataSource>
Vince Xu
Microsoft Online Community Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
![]() |
0 |
![]() |
Now all is working PERFECT!
THANK YOU!!!
(because of my post before... the path was wrong from the Handler.ashx)
![]() |
0 |
![]() |