How to save Images in Mysql Database or Image paths in database.

Thread is closed for posting
9 posts, 0 answers
  1. ravi
    ravi avatar
    8 posts
    Member since:
    Mar 2011

    Posted 21 Mar 2011 Link to this post

    Hi.. i want to know how to save images in database using RadUpload or RadAsyncUpload. and also i want to retrive it .. basically i'm making a Picture sharing site .. so please can u help me.. i'm beginner in and also i followed your demo link.. but its hard for me to understand.. 

    i've following scenario
    1. User may upload "N" no of photos.. to db.
    2 and has to retrive all his photos (Like gallery).

    Which method is best stroing path of image in DB or Image itself in the DB ... Please give me detailed information.. ;( please.. i'm struck with collge project :( :( please.
  2. Brian Shackelford
    Brian Shackelford avatar
    7 posts
    Member since:
    May 2008

    Posted 21 Mar 2011 Link to this post

    I have done this using ORM and SQL Server.  What are you using for your Data Access Layer?  I have never done this with MySQL, but we are exploring moving away from Microsoft SQL and using either Postgres or MySql so I would be glad to see if I can help you out as this is one of the criteria of the system we are using already and it would give me an excuse to figure it ou.
  3. ravi
    ravi avatar
    8 posts
    Member since:
    Mar 2011

    Posted 21 Mar 2011 Link to this post

    its ok . if u help me in Sql Server.. From Basic Steps.  i'll modify it for mysql. i'm using MySql Connector. everything is same as compared to the SQL Server.. it is really helpful if u provide a detailed information about my query.. user has to upload photo's to Db and then Has to retrive from db.. and Display Like a Gallery.. (To achive this which controls is needed ? ) . Please help me.. Really waiting for ur help to finish my project ;( :( please
  4. Brian Shackelford
    Brian Shackelford avatar
    7 posts
    Member since:
    May 2008

    Posted 23 Mar 2011 Link to this post

    I will be working on getting this to you this evening.  I have a project I just need to modify slightly and I can upload the whole sample to you.
  5. Brian Shackelford
    Brian Shackelford avatar
    7 posts
    Member since:
    May 2008

    Posted 25 Mar 2011 Link to this post

    I attached the code in full for the quick solution I could put together for you.  It has a single page (default.aspx) that has a Radgrid and RadUpload control on it.  Selecting the file and clicking Upload causes the file to be inserted into the Mysql database and then the Grid is refreshed and the file information is displayed along with the image.

    Make sure you have the Mysql.Data.MysqlClient assembly installed and referenced in your test project.  The project was created with VS 2010 and targeting .NET 4.0 using latest Q1 2011 tools.

    Also at the bottom is script used to create the MySql DB and table used in this example.  This should be enough to get you moving forward.  Let me know if you get stuck and I will do what I can to help - BUT as this is a college project, you probably need to handle the rest yourself ... remember instructors check these forums too ....

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Default" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
    <head runat="server">
        <telerik:RadStyleSheetManager id="RadStyleSheetManager1" runat="server" />
        <form id="form1" runat="server">
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
                <%--Needed for JavaScript IntelliSense in VS2010--%>
                <%--For VS2008 replace RadScriptManager with ScriptManager--%>
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
        <script type="text/javascript">
            //Put your JavaScript code here.
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <telerik:RadGrid ID="RadGrid1" runat="server" CellSpacing="0"
                DataSourceID="SqlDataSource1" GridLines="None" AutoGenerateColumns="False">
    <MasterTableView DataSourceID="SqlDataSource1"
    <CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>
    <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
    <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column">
            <telerik:GridBoundColumn DataField="idfiles" DataType="System.Int32"
                FilterControlAltText="Filter idfiles column" HeaderText="idfiles"
                ReadOnly="True" SortExpression="idfiles" UniqueName="idfiles">
            <telerik:GridBoundColumn DataField="filename"
                FilterControlAltText="Filter filename column" HeaderText="filename"
                SortExpression="filename" UniqueName="filename">
            <telerik:GridBoundColumn DataField="filetype"
                FilterControlAltText="Filter filetype column" HeaderText="filetype"
                SortExpression="filetype" UniqueName="filetype">
            <telerik:GridBoundColumn DataField="filesize"
                FilterControlAltText="Filter filesize column" HeaderText="filesize"
                SortExpression="filesize" UniqueName="filesize">
            <telerik:GridBoundColumn DataField="description"
                FilterControlAltText="Filter description column" HeaderText="description"
                SortExpression="description" UniqueName="description">
            <telerik:GridBinaryImageColumn DataField="filedata"
                FilterControlAltText="Filter column column" HeaderText="filedata"
                ImageHeight="200px" ImageWidth="200px" ResizeMode="Fit" UniqueName="column">
    <EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn>
    <FilterMenu EnableImageSprites="False"></FilterMenu>
    <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default"></HeaderContextMenu>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                ConnectionString="<%$ ConnectionStrings:filetestConnectionString %>"
                ProviderName="<%$ ConnectionStrings:filetestConnectionString.ProviderName %>"
                SelectCommand="SELECT * FROM files"></asp:SqlDataSource>
            <br />
            <br />
        <telerik:RadUpload ID="RadUpload1" Runat="server" InputSize="50"
        <br />
        <telerik:RadButton ID="RadButton1" runat="server" onclick="RadButton1_Click"
            Text="Upload File">

    using System;
    using System.Configuration;
    using Telerik.Web.UI;
    using MySql.Data.MySqlClient;
    public partial class Default : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
        protected void RadButton1_Click(object sender, EventArgs e)
            // Pull Saved Connection String from web.config.  Make sure to verify the connection string is correct
            // in the web.config.  It is important it is correct as if it is not, the datagrid will not show
            // the items correctly.
            string strConnection = ConfigurationManager.ConnectionStrings["filetestConnectionString"].ConnectionString;
            // Setup the Mysql.Data Conneciton - Note you need to have installed the MySql
            // .NET and Referenced the MySQL.NET Assembly
            MySqlConnection conn = new MySqlConnection(strConnection);
            string qry = "Insert into Files (filename,filedata,filetype,filesize) values (@filename, @filedata, @filetype, @filesize)";
            MySqlCommand cmd = new MySqlCommand(qry, conn);
            // Iterate through the array of files returned by RadUpload and process them
            foreach (UploadedFile f in RadUpload1.UploadedFiles)
                // Read the binary data into the bytes variable.  Found that since the InputStream will not take
                // a long variable, had to convert the file length to an int which is reason for extra line
                // of code.  If this is wrong - let me know ... works fine for me
                int l = (int)f.InputStream.Length;
                byte[] bytes = new byte[l];
                f.InputStream.Read(bytes, 0, l);
                // Add the parameters to the MySqlCommand and match it up to variables.  If not using the latest
                // .NET MySql, the named parameters may have a problem - not sure - haven't tested.  We use Telerik
                // Openaccess for all of our Datalayers now - but this just one method - could also use ODBC...
                cmd.Parameters.Add(new MySqlParameter("@filename", MySqlDbType.VarChar, 45)).Value = f.GetName();
                cmd.Parameters.Add(new MySqlParameter("@filedata", MySqlDbType.Binary)).Value = bytes;
                cmd.Parameters.Add(new MySqlParameter("@filetype", MySqlDbType.VarChar, 45)).Value = f.ContentType;
                cmd.Parameters.Add(new MySqlParameter("@filesize", MySqlDbType.VarChar, 45)).Value = f.ContentLength;
                // Open Connection, execute query, close connection
            // Refresh the Data Grid with Newly Uploaded items

    <?xml version="1.0"?>
            <add name="filetestConnectionString" connectionString="server=localhost;User Id=root;password=!mysql;Persist Security Info=True;database=filetest" providerName="MySql.Data.MySqlClient"/>
            <add key="Telerik.ScriptManager.TelerikCdn" value="Disabled"/>
            <add key="Telerik.StyleSheetManager.TelerikCdn" value="Disabled"/>
            <compilation debug="true" targetFramework="4.0"/>
                    <add tagPrefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI"/>
                <add path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" validate="false"/>
                <add path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" validate="false"/>
                <add path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" validate="false"/>
                <add path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" validate="false"/>
                <add path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" validate="false"/>
                <add name="RadUploadModule" type="Telerik.Web.UI.RadUploadHttpModule"/>
                <add name="RadCompression" type="Telerik.Web.UI.RadCompression"/>
            <validation validateIntegratedModeConfiguration="false"/>
            <modules runAllManagedModulesForAllRequests="true">
                <remove name="RadUploadModule"/>
                <add name="RadUploadModule" type="Telerik.Web.UI.RadUploadHttpModule" preCondition="integratedMode"/>
                <remove name="RadCompression"/>
                <add name="RadCompression" type="Telerik.Web.UI.RadCompression" preCondition="integratedMode"/>
                <remove name="ChartImage_axd"/>
                <add name="ChartImage_axd" path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" preCondition="integratedMode"/>
                <remove name="Telerik_Web_UI_SpellCheckHandler_axd"/>
                <add name="Telerik_Web_UI_SpellCheckHandler_axd" path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" preCondition="integratedMode"/>
                <remove name="Telerik_Web_UI_DialogHandler_aspx"/>
                <add name="Telerik_Web_UI_DialogHandler_aspx" path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" preCondition="integratedMode"/>
                <remove name="Telerik_RadUploadProgressHandler_ashx"/>
                <add name="Telerik_RadUploadProgressHandler_ashx" path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" preCondition="integratedMode"/>
                <remove name="Telerik_Web_UI_WebResource_axd"/>
                <add name="Telerik_Web_UI_WebResource_axd" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" preCondition="integratedMode"/>

    Sql Creation Script:
    delimiter $$
    CREATE DATABASE `filetest` /*!40100 DEFAULT CHARACTER SET latin1 */$$
    delimiter $$
    CREATE TABLE `files` (
      `idfiles` int(11) NOT NULL AUTO_INCREMENT,
      `filename` varchar(45) NOT NULL,
      `filedata` longblob NOT NULL,
      `filetype` varchar(45) NOT NULL,
      `filesize` varchar(45) DEFAULT NULL,
      `description` varchar(45) DEFAULT NULL,
      PRIMARY KEY (`idfiles`)
  6. ravi
    ravi avatar
    8 posts
    Member since:
    Mar 2011

    Posted 26 Mar 2011 Link to this post

    Thanks. Brain.. :) :) You Rockz,,,, the Code is working fine.. but i have a another small issue to retrive the images from db and make it as gallery... ?? you are using SqlDataSource..for RadGridview. ? na .. when i tried the same for Mysql  in Visual studio2010 it says some error. i have the latest dot net connector for mysql. still it's not allowing to add datasource in design time.. can u tell me how to display the images from db like a gallery..  Which controls should suit for this scenario. . and also how to use lightbox.. please this is the last help. from u .. rest i'll manage plz.. :( :(
  7. Brian Shackelford
    Brian Shackelford avatar
    7 posts
    Member since:
    May 2008

    Posted 28 Mar 2011 Link to this post

    Note that to use the SQLDataSource, you have to edit the query that is used to pull the information.  The designer interface does not produce the same query syntax that the MySql Datasource provider is expecting.

    As far as a gallery goes, I imagine it would be easiest to use the RadGrid control and perhaps use a custom item template to display the images.  In the case of doing something else, the RadBinaryImage control bound to the correct column should provide you an easy way to display the image.

    For downloading the image to the browser, I would have to look at the code I have at the office rather than rewrite it, just easier, but the upload was adapted from the following codeproject article, you can probably look at it and adapt the download code as well. 


    It should be pretty straight forward with a little tweaking, but again if you seem to still have trouble after the above article I will look at what I have at the office in the evening.

    A little more info on the SQLDataSource.  To get the MySQL to work as a Datasource for your project, I used the following in the web.config (Pay special attention to the providerName:

    <?xml version="1.0"?>
            <add name="filetestConnectionString" connectionString="server=localhost;User Id=root;password=!mysql;Persist Security Info=True;database=filetest" providerName="MySql.Data.MySqlClient"/>

    This will allow you to reference the Connection String when dropping the MySQL Datasource onto the page, but again the query syntax the desgner uses is still geared towards Microsoft SQL instead of mySQL - and while they are close, they are not exact.  So to get the SQLDatasource to work, you have to go into the ASPX page and edit the query in the code of the SQLDatasource to correctly pull the data from MySQL.  Open the ASPX page and look for the SQLDataSource tags:

    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:filetestConnectionString %>" 
        ProviderName="<%$ ConnectionStrings:filetestConnectionString.ProviderName %>" 
        SelectCommand="SELECT * FROM files"></asp:SqlDataSource>

    Notice the Select command needs to be modifed to fit syntax needed for MySQL.. Suggest testing the Query in the MySQL client just to verify it is correct.
  8. ravi
    ravi avatar
    8 posts
    Member since:
    Mar 2011

    Posted 02 Apr 2011 Link to this post

    Thank you for information.. I now succesfully retrive data from MYSql using SqlDataSource.. but i'm really confused about the displaying images in the Gallery. How to Use RadGrid Template.. to achive this goal.. please help me this one problem.. i done with all things... How to display images strored in database using Radgrid Template.. Can u give me a example for to achive this functionality.. this is last request from me.. i'll do all rest things.. please.. help me ... ;(
  9. Sebastian
    Sebastian avatar
    9934 posts

    Posted 07 Apr 2011 Link to this post

    Hello ravi,

    You can use either GridImageColumn or GridBinaryImageColumn for this purpose instead of a template column. Review the demos below for more info:

    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
Back to Top