Upload video or image in Database based on file type using C# in ASP.Net

Last Reply on Mar 21, 2017 10:52 AM By micah

Posted on Mar 21, 2017 05:20 AM

The challenges i face here is that if i upload video it will insert video name into imagename column in database column while the path is not inseted. So i want to make it in a way that if a user wants to upload only image it will insert the ImageName in ImageName colum in table, while if the user wants to upload only video it will insert the video path only in path column.

 

<asp:FileUpload ID="FileUploadpost" runat="server" /> 

 

CREATE TABLE [dbo].[USERPost](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UserName] [varchar](50) NULL,
	[ContentPost] [text] NULL,
	[SendDate] [datetime] NULL,
	[ImageName1] [nvarchar](500) NULL,
	
	[Path] [varchar](500) NULL,
 CONSTRAINT [PK_USERPost] PRIMARY KEY CLUSTERED 


code

 

protected void LinkBPOST_Click(object sender, EventArgs e)
    {

        if (this.Page.User.Identity.IsAuthenticated)
        {
            string username = this.Page.User.Identity.Name;
            {

                string tendString = TextBixcomment.Text.Trim();



                string strname = ""; // ADDED
                if (FileUploadpost.HasFile)
                {
                    strname = FileUploadpost.FileName.ToString();
                    FileUploadpost.PostedFile.SaveAs(Server.MapPath("~/UserImage/") + strname);
                } // <-- ADDED SO THAT WE JUST SAVE THE FILE IF THE FILE IS UPLOADED

                // THEN UNCHANGED WE SAVE THE DATA TO THE DB

                string str = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
                string getADPOST = "Insert INTO USERPost (UserName,ContentPost,ImageName1) values (@UserName,@ContentPost,@ImageName1)";
                // string getADPOST = "Insert INTO CommunityFollow  (MyUserName,FriendUserName,CommunityStatus) values (@MyUserName,@FriendUserName,1)";
                using (SqlConnection con = new SqlConnection(str))
                {

                    using (SqlCommand cmd = new SqlCommand(getADPOST, con))
                    {


                        // Get Filename from fileupload control
                        //   string filename = Path.GetFileName(FileUploadImage.PostedFile.FileName);
                        //  Save images into Images folder
                        //    Server.MapPath("~/UserImage/" + FileUploadImage.FileName);

                        //  cmd.Parameters.AddWithValue("@ImageName1", filename);
                        //    cmd.Parameters.AddWithValue("@ImageName1", "~/UserImage/" + filename);
                        cmd.Parameters.AddWithValue("@ContentPost", TextBixcomment.Text.Replace(Environment.NewLine, "<br/>").Trim());
                        cmd.Parameters.AddWithValue("@UserName", Session["userName"]);

                        cmd.Parameters.AddWithValue("@ImageName1", strname);
                        //cmd.Parameters.AddWithValue("@VideoName", strname);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();

                        //  Response.Redirect("Home.aspx");
                        string message = "Post submitted successfully.";
                        string script = "window.onload = function(){ alert('";
                        script += message;
                        script += "')};";
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
                    }
                }

            }
            // } ONE OF THIS DISAPPEARS AS WE CLOSED THE IF BLOCK MUCH EARLIER
        }

        this.Populatebooks();
    }

 

Posted on Mar 21, 2017 06:09 AM

Hi micah,

Refer the sample code and apply tha same logic in your code.

C#

string strname = "";
string extension = "";
string getADPOST = "";
string str = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
if (FileUploadpost.HasFile)
{
    strname = FileUploadpost.FileName;
    extension = System.IO.Path.GetExtension(strname);
    using (SqlConnection con = new SqlConnection(str))
    {
        SqlCommand cmd = new SqlCommand();
        // Image extension.
        if (extension.ToLower() == ".jpg" || extension.ToLower() == ".png" || extension.ToLower() == ".gif" || extension.ToLower() == ".jpeg")
        {
            getADPOST = "Insert INTO USERPost (UserName,ContentPost,ImageName1) values (@UserName,@ContentPost,@ImageName1)";
            cmd.Parameters.AddWithValue("@ContentPost", TextBixcomment.Text.Replace(Environment.NewLine, "<br/>").Trim());
            cmd.Parameters.AddWithValue("@UserName", Session["userName"]);
            cmd.Parameters.AddWithValue("@ImageName1", strname);
        }
        // Video extension.
        else if (extension.ToLower() == ".mp4" || extension.ToLower() == ".wmv" || extension.ToLower() == ".vob" || extension.ToLower() == ".dat")
        {
            getADPOST = "Insert INTO USERPost (UserName,ContentPost,Path) values (@UserName,@ContentPost,@Path)";
            cmd.Parameters.AddWithValue("@ContentPost", TextBixcomment.Text.Replace(Environment.NewLine, "<br/>").Trim());
            cmd.Parameters.AddWithValue("@UserName", Session["userName"]);
            cmd.Parameters.AddWithValue("@Path", "~/Videos/" + strname);
        }
        cmd.CommandText = getADPOST;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Connection = con;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

 


Posted on Mar 21, 2017 10:52 AM

i have seen the error, you didnt add this line of code

 

 

 FileUploadpost.PostedFile.SaveAs(Server.MapPath("~/UserImage/") + strname);
                    FileUploadpost.PostedFile.SaveAs(Server.MapPath("~/path/") + strname);

full code

 

 protected void LinkBPOST_Click(object sender, EventArgs e)
    {

        if (this.Page.User.Identity.IsAuthenticated)
        {
            string username = this.Page.User.Identity.Name;
            {

                string tendString = TextBixcomment.Text.Trim();

                string strname = "";
                string extension = "";
                string getADPOST = "";
                string str = ConfigurationManager.ConnectionStrings["micconn"].ConnectionString;
                if (FileUploadpost.HasFile)
                {
                    strname = FileUploadpost.FileName.ToString();
                    FileUploadpost.PostedFile.SaveAs(Server.MapPath("~/UserImage/") + strname);
                    FileUploadpost.PostedFile.SaveAs(Server.MapPath("~/path/") + strname);
                    extension = System.IO.Path.GetExtension(strname);
                    using (SqlConnection con = new SqlConnection(str))
                    {
                        SqlCommand cmd = new SqlCommand();
                        // Image extension.
                        if (extension.ToLower() == ".jpg" || extension.ToLower() == ".png" || extension.ToLower() == ".gif" || extension.ToLower() == ".jpeg")
                        {
                            getADPOST = "Insert INTO USERPost (UserName,ContentPost,ImageName1) values (@UserName,@ContentPost,@ImageName1)";
                            cmd.Parameters.AddWithValue("@ContentPost", TextBixcomment.Text.Replace(Environment.NewLine, "<br/>").Trim());
                            cmd.Parameters.AddWithValue("@UserName", Session["userName"]);
                            cmd.Parameters.AddWithValue("@ImageName1", strname);
                        }
                        // Video extension.
                        else if (extension.ToLower() == ".mp4" || extension.ToLower() == ".wmv" || extension.ToLower() == ".vob" || extension.ToLower() == ".dat")
                        {
                            getADPOST = "Insert INTO USERPost (UserName,ContentPost,Path) values (@UserName,@ContentPost,@Path)";
                            cmd.Parameters.AddWithValue("@ContentPost", TextBixcomment.Text.Replace(Environment.NewLine, "<br/>").Trim());
                            cmd.Parameters.AddWithValue("@UserName", Session["userName"]);
                            cmd.Parameters.AddWithValue("@Path", "/path/" + strname);
                        }
                        cmd.CommandText = getADPOST;
                        cmd.CommandType = System.Data.CommandType.Text;
                        cmd.Connection = con;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        string message = "Post submitted successfully.";
                        string script = "window.onload = function(){ alert('";
                        script += message;
                        script += "')};";
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
                    }
                }