Code to upload Audio/Image Files in Sql Server
First Add FileUpload Control in your Aspx Page, Then use this code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.IO;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Int32 intAudioSize = 0;
string strAudioType = null;
Stream AudioStream = null;
// Gets the Size of the Audio
intAudioSize = FileUpload1.PostedFile.ContentLength;
// Gets the Audio Type
strAudioType = FileUpload1.PostedFile.ContentType;
// Reads the Audio
AudioStream = FileUpload1.PostedFile.InputStream;
byte[] AudioContent = new byte[intAudioSize + 1];
int intStatus = 0;
intStatus = AudioStream.Read(AudioContent, 0, intAudioSize);
// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
SqlCommand myCommand = new SqlCommand("Insert into AudioTable (Audio,AudioType) Values (@Audio,@AudioType)", myConnection);
// Mark the Command as a SPROC/Query
myCommand.CommandType = CommandType.Text;
// Add Parameters to SPROC
SqlParameter prmAudio = new SqlParameter("@Audio", SqlDbType.Image);
prmAudio.Value = AudioContent;
myCommand.Parameters.Add(prmAudio);
SqlParameter prmAudioType = new SqlParameter("@AudioType", SqlDbType.VarChar, 255);
prmAudioType.Value = strAudioType;
myCommand.Parameters.Add(prmAudioType);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Write("New audio file uploaded successfully!");
}
catch (SqlException SQLexc)
{
Response.Write("Insert Failed. Error Details are: " + SQLexc.ToString());
}
}
}
}
Hi Its A Great Article.
ReplyDeleteCan U Tell Me How to Retrieve That Audio File From SqlServer2005.
In SqlServer 2005 I have Inserted 3 Audio Files (Voice1,Voice2,Voice3) In a Row.
I have a Button "Retrieve" in Asp.Net,C#.When I press the Retrieve Button Depending on the Row I have Selected It Has to Play Me all the Audios.
Thanks in Advance