【问题标题】:Uploading multiple images to the server and inserting their file names in a database将多个图像上传到服务器并将它们的文件名插入数据库
【发布时间】:2014-07-24 17:25:57
【问题描述】:

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

内容页

 <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

【问题讨论】:

  • 请看答案

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


【解决方案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();

         }

        }

   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多