ASP.net后台程序中的图片上传到数据库中的路径问题

时间:2022-11-28 19:00:46

index.aspx 页面时这样的

 

        <asp:TextBox ID="tbxImage" runat="server" TabIndex="5" Font-Size="Larger" Visible="false"></asp:TextBox>
                             <div>
                                <asp:FileUpload ID="loFile" runat="server" />
                            </div>

 

index.aspx.cs 代码是这样的

content = Request.Form.Get("content");
        string strFilePathName = loFile.PostedFile.FileName;  //获取完整的路径
        string strFileName = Path.GetFileName(strFilePathName);//获取图片的名称
        int FileLength = loFile.PostedFile.ContentLength;//获取图片的大小

        if (FileLength <= 0)//判断是否有图片
            return;

        try
        {

            Byte[] FileByteArray = new Byte[FileLength];//用图片的长度来初始化一个字节数组存储临时的图片文件

            Stream StreamObject = loFile.PostedFile.InputStream; //建立文件流对象


            StreamObject.Read(FileByteArray, 0, FileLength);// 读取图片数据到临时存储体FileByteArray,0为数据指针位置,fileLength为数据长度


            string strCon = ConfigurationManager.ConnectionStrings["hospitalConnectionString"].ConnectionString;
            SqlConnection Con = new SqlConnection(strCon);
            String SqlCmd = "INSERT INTO [NewsInfo](nContents,nTitle,nDate,nStyle,nImages) VALUES (@nContents,@nTitle,@nDate,@nStyle,@nImages)";
            SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
            CmdObj.Parameters.Add("@nImages", SqlDbType.Binary, FileLength).Value = FileByteArray;//将二进制的图片赋值给@Image
            CmdObj.Parameters.Add("@nContents", SqlDbType.NText).Value = content;
            CmdObj.Parameters.Add("@nTitle", SqlDbType.NVarChar).Value = tbxTitle.Text;
            CmdObj.Parameters.Add("@nDate", SqlDbType.DateTime).Value = Convert.ToDateTime(txtDate.Text.ToString());
            CmdObj.Parameters.Add("@nStyle", SqlDbType.NChar).Value = DropDownListStyle.SelectedValue;

            Con.Open();
            CmdObj.ExecuteNonQuery(); //执行Sqlcommand
            Con.Close();//关闭链接

            Response.Redirect("ArticleMng.aspx");//跳转页面
        }
        catch (Exception ex)//抛出异常
        {
            throw ex;
        }

 

 请问怎么样上传到数据库里面,并上传到指定项目的一个存放图片的路径下面,同时要更改数据库的路径把数据库中图片上传的原始路径改成在项目中指定的存放图片的位置。

  我是初学者,请大家帮忙解决一下!谢谢诶~~~