将多个图像上传到服务器并在数据库中插入它们的文件名

本文关键字:插入 数据库 文件名 图像 服务器 | 更新日期: 2023-09-27 18:14:38

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

内容页

 <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

将多个图像上传到服务器并在数据库中插入它们的文件名

这是你需要绑定参数的解决方案。

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();
         }
        }
   }