Library tutorials & articles

Uploading Images to a Database

Full Source Code

Image SQL

CREATE TABLE [dbo].[image] (
    [img_pk] [int] IDENTITY (1, 1) NOT NULL ,
    [img_name] [varchar] (50) NULL ,
    [img_data] [image] NULL ,
    [img_contenttype] [varchar] (50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[image] WITH NOCHECK ADD
CONSTRAINT [PK_image] PRIMARY KEY NONCLUSTERED
(
    [img_pk]
) ON [PRIMARY] GO

UploadImage.aspx

<%@ Page language="c#" Src="UploadImage.aspx.cs" Inherits="DBImages.UploadImage" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
</HEAD>
<body bgcolor=#ffffff>
<form enctype="multipart/form-data" runat=server id=form1 name=form1>
<h3>The ASPFree Friendly Image Uploader</h3>
Enter A Friendly Name<input type=text id=txtImgName runat="server" >
<asp:RequiredFieldValidator id=RequiredFieldValidator1 runat="server" ErrorMessage="Required" ControlToValidate="txtImgName"></asp:RequiredFieldValidator>
<br>Select File To Upload:
<input id="UploadFile" type=file runat=server>
<asp:button id=UploadBtn Text="Upload Me!" OnClick="UploadBtn_Click" runat="server"></asp:button>
</form>

</body>
</HTML>

UploadImage.aspx.cs (codebehind file)

using System;
using System.Configuration;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace DBImages
{
    public class UploadImage : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Button UploadBtn;
        protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
        protected System.Web.UI.HtmlControls.HtmlInputText txtImgName;
        protected System.Web.UI.HtmlControls.HtmlInputFile UploadFile;
        public UploadImage() { }
        private void Page_Load(object sender, System.EventArgs e){ }
        public void UploadBtn_Click(object sender, System.EventArgs e)
        {
            if (Page.IsValid) //save the image
            {
                Stream imgStream = UploadFile.PostedFile.InputStream;
                int imgLen = UploadFile.PostedFile.ContentLength;
                string imgContentType = UploadFile.PostedFile.ContentType;
                string imgName = txtImgName.Value;
                byte[] imgBinaryData = new byte[imgLen];
                int n = imgStream.Read(imgBinaryData,0,imgLen);
                int RowsAffected = SaveToDB( imgName, imgBinaryData,imgContentType);
                if ( RowsAffected>0 )
                {
                    Response.Write("<BR>The Image was saved");
                }
                else
                {
                    Response.Write("<BR>An error occurred uploading the image");
                }
            }
        }

        private int SaveToDB(string imgName, byte[] imgbin, string imgcontenttype)
        {
            //use the web.config to store the connection string
            SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
            SqlCommand command = new SqlCommand( "INSERT INTO Image (img_name,img_data,img_contenttype) VALUES ( @img_name, @img_data,@img_contenttype )", connection );
            SqlParameter param0 = new SqlParameter( "@img_name", SqlDbType.VarChar,50 );
            param0.Value = imgName;
            command.Parameters.Add( param0 );
            SqlParameter param1 = new SqlParameter( "@img_data", SqlDbType.Image );
            param1.Value = imgbin;
            command.Parameters.Add( param1 );
            SqlParameter param2 = new SqlParameter( "@img_contenttype", SqlDbType.VarChar,50 );
            param2.Value = imgcontenttype;
            command.Parameters.Add( param2 );
            connection.Open();
            int numRowsAffected = command.ExecuteNonQuery();
            connection.Close();
            return numRowsAffected;
        }
    }
}

Web.Config

<configuration>
    <appSettings>
            <add key="DSN" value="server=localhost;uid=sa;pwd=;Database=aspfree"/>
    </appSettings>
    <system.web>
            <customErrors mode="Off" />
    </system.web>
</configuration>

Comments

  1. 20 Mar 2009 at 14:52
    Hi can i upload images using open dialog in asp.net by selecting multiple images at a time by single button click as like we have open file dialog in windows appllication
  2. 15 Jun 2006 at 13:52

    This may sound weird but I think I'm the only one not having perfect success with this.

    I'm getting a System.NullReferenceException: Object reference not set to an instance of an object.
    on the line


    Stream imgStream = UploadFile.PostedFile.InputStream;

    [NullReferenceException: Object reference not set to an instance of an object.]
    DBImages.UploadImage.BtnUpload_Click(Object sender, EventArgs e) in c:\Inetpub\wwwroot\official-certify\Media\SubmitJon.aspx.cs:70
    System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
    System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
    System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
    System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
    System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33

    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102










    I'm not sure why I'm getting this error. I copied the code verbatum and then added references for my other fields that I'm pulling in.

    I have no idea what the stack trace is all about, like I understand stacks, but the way these are formatted makes no sense to me, although here's what's in it maybe you guys will know.

    ((my button is exactly the same just named BtnUpload as opposed to UploadBtn.))



    If anyone could help it would be greatly appreciated. It's been driving me nuts I've run into a bunch of other errors that I've fixed, mostly missing a ";" but I've taken care of them all, this is the only one I haven't figured out yet (well unless there's more after this one is fixed)

    Thanks in advance for the help








  3. 02 Nov 2005 at 09:48

    The easiest way to upload and resize an image to the internet and automatically create thumbnails is I-Load.
    I-Load is a FREE ASP.NET web control with numerous benefits and features.
    You can download I-Load (it's FREE!) and view an online demo here:


    http://www.radactive.com/en/Products/ILoad/Overview.aspx

  4. 03 Sep 2005 at 08:39
    Hi,   Whts the benifit of uploading images in database server when i can place images on web server in my directory and accesss them. Reply soon.
  5. 02 Aug 2005 at 11:06
    The explanatory text says "The first interesting point about our webform, is the attribute "enctype". Enctype tells the browser and server that we will be uploading some type of binary data" but I don't see enctype in the code samples. Have I missed something?

    Les
  6. 08 Jul 2005 at 16:13

    Better control of file updates.  On file server, anybody can update files without letting anyone know about it.  If you store a file inside SQL database, it will show who last updated files, inform users when it expires, requiring updates and so on.  I administer 230 manual documents that shows original creator, date of implementation, maintainer and updated date.  Very useful and uniform in updates and maintenance.


  7. 18 May 2005 at 14:57

    i have been able to implement this and i now upload all sorts of documents including images into my sql server database. i now need to retrieve the document in the original format (.doc, .xls, .jpg, etc). pls, i do i achieve that?

  8. 28 Dec 2004 at 05:32

    Hello,


    I need some more idea on this topic. What is benifit to store data into SQL server (means into BLOB chartype in SQL). Why can not we just store file on to PC and just add link name into SQL.


    Please can anybody give me this ans.


    Thanks

  9. 20 Sep 2003 at 22:19

    Ok,


    Im sorta new to ASP.Net and Ive got the image upload to blob working ...


    But for this to be moreso practical, it would be nice to see the ability to upload into another field, the thumbnail automatically generated from the blob data. (or when it gets uploaded).


    Can someone help or point me in the right direction?!?!


    Im desperate

  10. 01 Jan 1999 at 00:00

    This thread is for discussions of Uploading Images to a Database.

Leave a comment

Sign in or Join us (it's free).

Dave Wanta
AddThis

Related podcasts

  • 2008 Year in Review

    CodeCast Episode 9: 2008 Year in ReviewOur special 2008 year in review episode with hosts Ken Levy and Markus Egger, joined by special guest co-host Rick Strahl of West Wind Technologies. Topics · Visual Studio (@ 2:37) · Languages (@ 6:28) · SQL Server (@ 10:15) · ...

Events coming up

  • Nov 19

    SQLBits V

    Newport, United Kingdom

    SQLBits is Europe's largest SQL Server conference, and SQLBits V will be the biggest and best yet. On November 19th we are holding a day of pre-conference seminars; on November 20th we have a pay-to-attend day of SQL Server 2008 and R2 content; and on Saturday November 21st we have our usual free community conference.

Want to stay in touch with what's going on? Follow us on twitter!