将注册表格中的图像上传到本地数据库

时间:2018-11-22 13:15:31

标签: c# asp.net webforms

我希望用户能够在注册时上传图像。我不太正确,希望您能提供帮助。我正在使用asp.net c#,并在Visual Studio中使用本地数据库。

到目前为止,这就是我的HTML:

<tr>
<td class="auto-style3">Image </td>
<td class="auto-style4">
<asp:FileUpload ID="FileUpload1" runat="server"  />

后端:

protected void Submit_Click(object sender, EventArgs e)
    {


            SqlConnection conn = new SqlConnection   (ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            conn.Open();
        SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM Users WHERE ([Username] = @user)", conn);
        check_User_Name.Parameters.AddWithValue("@user", TextBoxUN.Text);
        int UserExist = (int)check_User_Name.ExecuteScalar();

        if (UserExist > 0)
        {
            Response.Write("Username already exists");

        }
        else
        {

string insertQuery = "insert into Users   (FirstName,SecondName,UserName,Password,Email,ProductOwner,ScrumMaster,Developer,ConfirmPassword, Image) values(@FName,@SName,@UserName,@Password,@Email,@ProductOwner,@ScrumMaster,@Developer,@ConfirmPassword,@Image)";
SqlCommand com = new SqlCommand(insertQuery, conn);

com.Parameters.AddWithValue("@FName", TextBoxFN.Text);
com.Parameters.AddWithValue("@SName", TextBoxSN.Text);
com.Parameters.AddWithValue("@UserName", TextBoxUN.Text);
com.Parameters.AddWithValue("@Password", TextBoxPass.Text);
com.Parameters.AddWithValue("@ConfirmPassword", TextBoxConPass.Text);
com.Parameters.AddWithValue("@Email", TextBoxEmail.Text);
com.Parameters.AddWithValue("@ProductOwner", CheckBoxProduct.Checked.ToString());
com.Parameters.AddWithValue("@ScrumMaster", CheckBoxScrum.Checked.ToString());

com.Parameters.AddWithValue("@Developer", CheckBoxDeveloper.Checked.ToString());
                com.Parameters.Add("@Image");
</td>
</tr>

1 个答案:

答案 0 :(得分:2)

您需要将图像保存在磁盘上

if (FileUpload1.HasFile)
{
    // you have to create a folder in which to store the images
    var savePath = Path.Combine(Server.MapPath("~/UserImages"), FileUpload1.FileName;
    FileUpload1.SaveAs(savePath);
}

您需要将文件名保存在数据库中

com.Parameters.Add("@Image", FileUpload1.FileName);

您必须确保该文件夹不包含同名文件。