upload image to mysqldatabase using ajaxfileupload control in ASP.Net

Last Reply on Jul 25, 2016 08:13 AM By dharmendr

Posted on Jul 25, 2016 02:03 AM

is there any Tutorial on how to upload image into mysqldatabase using ajaxfileupload?

Posted on Jul 25, 2016 08:13 AM Modified on on Jul 25, 2016 10:04 AM

Hi firdaus,

Refer the below code.

Code

protected void OnUploadComplete(object sender, AjaxFileUploadEventArgs e)
{
    string filename = Path.GetFileName(e.FileName);
    string contentType = string.Empty;
    string content = e.ContentType.ToLower();
    switch (content)
    {
        case ".jpg":
            contentType = "image/jpeg";
            break;
        case ".pdf":
            contentType = "application/pdf";
            break;
        case ".doc":
            contentType = "application/vnd.ms-word";
            break;
        case ".docx":
            contentType = "application/vnd.ms-word";
            break;
        case ".xls":
            contentType = "application/vnd.ms-word";
            break;
        case ".xlsx":
            contentType = "application/vnd.ms-word";
            break;
        default:
            contentType = "null";
            break;
    }

    using (Stream fs = e.GetStreamContents())
    {
        using (BinaryReader br = new BinaryReader(fs))
        {
            byte[] bytes = br.ReadBytes((Int32)fs.Length);
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                string query = "INSERT INTO tblFiles(Name, ContentType, Data) VALUES (@FileName, @ContentType, @Content)";
                using (MySqlCommand cmd = new MySqlCommand(query))
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@FileName", filename);
                    cmd.Parameters.AddWithValue("@ContentType", contentType);
                    cmd.Parameters.AddWithValue("@Content", bytes);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
    }
    Response.Redirect(Request.Url.AbsoluteUri);
}

HTML

<ajaxToolkit:ToolkitScriptManager runat="server">
</ajaxToolkit:ToolkitScriptManager>
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" MaximumNumberOfFiles="5"
    Width="400px" OnUploadComplete="OnUploadComplete" />