将多个映像上载到服务器并将其文件名插入数据库

时间:2014-07-24 09:07:37

标签: c# asp.net vb.net file-upload

我有以下代码将多个图像上传到服务器并将其名称插入数据库。

内容页

 <asp:FileUpload runat="server" ID="UploadImages" AllowMultiple="true" />
    <asp:Button runat="server" ID="uploadedFile" Text="Upload" OnClick="uploadFile_Click" />
    <asp:Label ID="listofuploadedfiles" runat="server" />

代码背后

    protected void uploadFile_Click(object sender, EventArgs e)
     {

       if (UploadImages.PostedFile != null)

       {

        string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; 
        SqlConnection con = new SqlConnection(strConnString);
        SqlCommand cmd = new SqlCommand();

        try
        {
            con.Open();        

           foreach (HttpPostedFile uploadedFile in this.UploadImages.PostedFiles)
           {
                string newname = System.DateTime.Now.ToString("yyMMdd-hhmmss-") + uploadedFile.FileName;
                uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("/Images/Editors/BG/"), newname));
                listofuploadedfiles.Text += string.Format("<br /><img width='100px' src='/Images/Editors/BG/{0}'/>{0}<br clear='all'/>", newname);


               cmd.Connection = con; 
               cmd.CommandText = "INSERT INTO BackgroundImages([BG_fileName], [IDuser]) VALUES(" + newname + "," + HttpContext.Current.User.Identity.GetUserId() + ")";
               cmd.ExecuteNonQuery();
           }
        }
        catch (Exception ex)
        {
            Response.Write("Error while inserting record on table..." + ex.Message + "Insert Records");
        }
        finally
        {
            con.Close();
            con.Dispose();

         }

        }

   }

我能够将图像上传到服务器,但没有任何内容添加到数据库中。我没有收到任何错误。怎么了?

实际上我把上面的代码从VB翻译成了C#。我确定我错过了一些东西,因为我还不熟悉C#。以下VB代码运行良好:

Protected Sub uploadFile_Click(sender As Object, e As EventArgs)

    If UploadImages.HasFiles Then

        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString)
        Dim cmd As New SqlCommand
        Try
            con.Open()

            Dim newname As String

            For Each uploadedFile As HttpPostedFile In UploadImages.PostedFiles

                newname = System.DateTime.Now.ToString("yyMMdd-hhmmss-") + uploadedFile.FileName
                uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Images/"), newname))
                listofuploadedfiles.Text += [String].Format("<br /><img width='100px' src='Images/{0}'/>{0}<br clear='all'/>", newname)

                cmd.Connection = con
                cmd.CommandText = "INSERT INTO Images([filename], [userid]) VALUES('" & newname & "','" & userid & "' )"
                cmd.ExecuteNonQuery()
            Next

        Catch ex As Exception
            'MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
        Finally
            con.Close()
        End Try

    End If
End Sub

1 个答案:

答案 0 :(得分:1)

以下是使用该参数绑定参数所需的解决方案。

protected void uploadFile_Click(object sender, EventArgs e)
     {

       if (UploadImages.PostedFile != null)

       {

           string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; 
        SqlConnection con = new SqlConnection(strConnString);
        con.Open();
        try
        {             

           foreach (HttpPostedFile uploadedFile in this.UploadImages.PostedFiles)
           {
                string newname = System.DateTime.Now.ToString("yyMMdd-hhmmss-") + uploadedFile.FileName;
                uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("/Images/Editors/BG/"), newname));
                listofuploadedfiles.Text += string.Format("<br /><img width='100px' src='/Images/Editors/BG/{0}'/>{0}<br clear='all'/>", newname);


              SqlCommand cmd = new SqlCommand();
              cmd.Connection = con;
              cmd.CommandType = CommandType.Text;
              cmd.CommandText = @"INSERT INTO BackgroundImages(BG_fileName, IDuser)
              VALUES(@param1,@param2)";  

              cmd.Parameters.AddWithValue("@param1", newname);  
              cmd.Parameters.AddWithValue("@param2", HttpContext.Current.User.Identity.GetUserId());
              cmd.ExecuteNonQuery();  
           }
        }
        catch (Exception ex)
        {
            Response.Write("Error while inserting record on table..." + ex.Message + "Insert Records");
        }
        finally
        {
            con.Close();
            con.Dispose();

         }

        }

   }