Monday, March 24, 2008

How to upload a File




In This , How to upload a file. i saved filepath in database, files in filesfolder

Stored Procedure:

ALTER procedure [dbo].[spfiles_topic](@username varchar(50),@topic varchar(50),

@subject varchar(50),@filepath varchar(50))

as begin

insert into files_topic(username,topic,subject,filepath)

values(@username,@topic,@subject,@filepath)

end

In Default.aspx page take 4 lables ,3 textboxes and 1 fileuploadcontrol

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page

{

SqlConnection sqlcon = new SqlConnection("user id=sa;password=satish_574;database=subbu;data source=localhost");

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

SqlCommand sqlcm = new SqlCommand();

sqlcm.Connection = sqlcon;

sqlcm.CommandType = CommandType.StoredProcedure;

sqlcm.CommandText = "spfiles_topic";

SqlParameter @username, @topic, @subject, @filepath;

username = sqlcm.Parameters.Add("@username", SqlDbType.VarChar);

username.Direction = ParameterDirection.Input;

username.Value = TextBox1.Text;

topic=sqlcm.Parameters.Add("@topic",SqlDbType.VarChar);

topic.Value=TextBox2.Text;

topic.Direction=ParameterDirection.Input;

subject=sqlcm.Parameters.Add("@subject",SqlDbType.VarChar);

subject.Direction=ParameterDirection.Input;

subject.Value=TextBox3.Text;

if(IsPostBack)

{

Boolean fileOK = false;

String path = Server.MapPath("~/filesfolder/");

if (FileUpload1.HasFile)

{

String fileExtension =

System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();

String[] allowedExtensions =

{".doc", ".rtf", ".pdf", ".jpg"};

for (int i = 0; i <>

{

if (fileExtension == allowedExtensions[i])

{

fileOK = true;

}

}

}

if (fileOK)

{

try

{

FileUpload1.PostedFile.SaveAs(path

+ FileUpload1.FileName);

Label5.Text = "File uploaded!";

}

catch (Exception ex)

{

Label5.Text = "File could not be uploaded.";

}

}

else

{

Label5.Text = "Cannot accept files of this type.";

}

}

string s = "~/filesfolder/" + FileUpload1.FileName;

filepath = sqlcm.Parameters.Add("@filepath", SqlDbType.VarChar);

filepath.Value = s;

filepath.Direction = ParameterDirection.Input;

sqlcon.Open();

sqlcm.ExecuteNonQuery();

sqlcon.Close();

}

}


No comments :

Post a Comment