上传图片,扩展程序无效

时间:2011-11-07 13:41:08

标签: asp.net sql vb.net

我正在尝试上传图像并将图像名称保存在数据库中作为会话名称,扩展名为.jpg 我遇到的问题是只保存在数据库中的图像名称而不是扩展名。我正在使用此代码

Dim strPath As String = Server.MapPath("~/UserPics/")
        If AsyncFileUpload1.HasFile Then
            AsyncFileUpload1.SaveAs(strPath & Session("UserName").ToString() & ".jpg")
            lblUploadMessage.Text = "You uploaded " + AsyncFileUpload1.FileName
            con.Open()
            Dim objCmd As New SqlCommand("insert into regist( image1) values ('" & Session("UserName").ToString() & "')", con)
            objCmd.ExecuteNonQuery()
            con.Close()
        Else
            lblUploadMessage.Text = "Please select an image first"
            Return
        End If

2 个答案:

答案 0 :(得分:3)

您没有插入要保存的相同字符串,您必须添加扩展名,请参阅下文。另外,从发布的文件中添加扩展名而不是硬编码:

Dim objCmd As New SqlCommand("insert into regist(image1) values ('" & _
    Session("UserName").ToString() & _
    System.IO.Path.GetExtension(AsyncFileUpload1.PostedFile.FileName) & "')", con)

请将您的代码更改为使用参数以防止SQL注入攻击:

Dim objCmd As New SqlCommand(con)
Dim sql As String = "insert into regist(image1) values (@image)"
Dim param(1) As SqlParameter
param(0) = New SqlParameter("@image", SqlDbType.VarChar)
param(0).Value = Session("UserName").ToString() & _
      System.IO.Path.GetExtension(AsyncFileUpload1.PostedFile.FileName);
objCmd.Parameters.AddRange(param)
objCmd.ExecuteNonQuery()
con.Close()

答案 1 :(得分:-1)

更改

Dim objCmd As New SqlCommand("insert into regist( image1) values ('" & Session("UserName").ToString() & "')", con)

Dim objCmd As New SqlCommand("insert into regist( image1) values ('" & Session("UserName").ToString() & ".jpg" & "')", con)