Saturday, April 02, 2005

Uploading Image to the Server Folder and Displaying in the DataList Control

Just wrote a few lines of code to upload the image selected by the user to the Server's Folder and display it in the DataList control. This sort of functionality can be used for making Photo Albums.


Button Click Code:

private void Button1_Click(object sender, System.EventArgs e)
{
// Gets the whole Path
string filePath = File1.PostedFile.FileName;
Response.Write(filePath);
// Gets only the file name
string fileName = System.IO.Path.GetFileName(filePath);
try
{
// Path to the server's folder
string serverFilePath = @"C:\ServerFolder\"+fileName;

string fileSize = File1.PostedFile.ContentLength.ToString();
File1.PostedFile.SaveAs(serverFilePath);
// Adds in the database
string connectionString = (string) ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection myConnection = new SqlConnection(connectionString);
SqlCommand myCommand = new SqlCommand("InsertPicture",myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@Name",SqlDbType.NVarChar,50);
myCommand.Parameters["@Name"].Value = txtName.Text;
myCommand.Parameters.Add("@Description",SqlDbType.NVarChar,500);
myCommand.Parameters["@Description"].Value = txtDescription.Text;
myCommand.Parameters.Add("@Size",SqlDbType.NVarChar,50);
myCommand.Parameters["@Size"].Value = fileSize;
myCommand.Parameters.Add("@Path",SqlDbType.NVarChar,100);
myCommand.Parameters["@Path"].Value = serverFilePath;
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Write("File Uploaded");
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}

DataList code to display the Image on the Screen:


Here Path is the path to the server Check the button click code.
Page_Load Event Code:
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
string connectionString = (string) ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Pictures",myConnection);
DataSet ds = new DataSet();
ad.Fill(ds,"Pictures");
DataList1.DataSource = ds;
DataList1.DataBind();
}
}
Binding to the DataList Control:

This blog is not letting me post the code. Hint is to use DataBinder.Eval in the html code.




No comments: