Professional Documents
Culture Documents
Net
31 Mar 2013 Mudassar Khan
ASP.Net SQL Server
Here Mudassar Ahmed Khan has explained with an example and attached sample code, how to upload and save (insert) images to
SQL Server Database in ASP.Net using C# and VB.Net.
Download
ASPSnippets
Like
I have already explained how to save and retrieve files in SQL Server database using ASP.Net in my article Save and Retrieve Files
from SQL Server Database using ASP.Net
This article is an extension of the same since was frequently asked on how to save file directly to database using the ASP.Net
FileUpload Control
You can upload any files like images, Word document. Excel document, Portable Document Format (PDF), Text Files sand save them
to Database
Database Design
Here I have created a Database called dbFiles and it has a table called tblFiles.
It has 4 Fields. The complete description is available in the Figure below
As you can see above for the id field I have set Identity Specification true, so that it automatically increments itself.
Field
Relevance
id
Identification Number
Name
File Name
Content Type
Data
Connection String
Below is the connection string to the database. You can modify it to suit yours
<connectionStrings>
<add name="conString" connectionString="Data Source=.\SQLEXPRESS;database=dbFiles; Integrated Security=true"/>
</connectionStrings >
To start with I have added a FileUpload control, a button and a Label to show messages
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClick="btnUpload_Click" />
<br />
<asp:Label ID="lblMessage" runat="server" Text=""
Font-Names = "Arial"></asp:Label>
And here is the snippet which is called on the Upload Button Click event
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
VB.Net
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 = FileUpload1.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 tblFiles" _
& "(Name, ContentType, Data)" _
& " 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
The above code simply reads the uploaded File as Stream and then converts the Stream to Byte array using Binary Reader and then
the finally the byte arrays is saved to the database InsertUpdateData method executes the query to save the data in database
The InsertUpdateData function is given below
C#
private Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
VB.Net
This completes the article. You can download the source code in VB.Net and C# from the link below.
Download
Related Articles
Save and Retrieve Files from SQL Server Database using ASP.Net
Here Mudassar Ahmed Khan has explained how to save file as binary data inside SQL Server database and also how to retreive them
and reconvert to their respective formats using VB.net amd C#.
Comments
ali
May 03, 2013 03:05 AM
Mudassar Khan
May 03, 2013 07:05 AM
Nirav
Dec 05, 2013 09:12 AM
ashish
Jan 17, 2014 11:01 AM
very good
Churni
Feb 08, 2014 12:02 PM
Thank you
Worked a treat
More
Add Comments
You can add your comment about this article using the form below. Make sure you provide a valid email
address
else you won't be notified when the author replies to your comment
Please note that all comments are moderated and will be deleted if they are
Not relavant to the article
Spam
Advertising campaigns or links to other sites
Abusive content.
Please do not post code, scripts or snippets.
Name
Name
Email
Email
Comment
Comment
Security code*:
Add Comment
Subscribe
Subscribe
2014 www.aspsnippets.com All rights reserved | Privacy Policy | Powered by Excelasoft Solutions